JavaScript Arrays Masterclass

Pro Members Only

This lesson is available if you have an active subscription.

Alternatively, some member might be able to gift it to you.

If you already have a subscription, you can sign in.

Professional Modern JavaScript Lessons

1.Course Intro
free
⏱️ 1:13
2.Setup & Tooling
free
⏱️ 3:32
3.Debugger Statements and Breakpoints
free
⏱️ 2:17
4.Primitive Data Types and Values
free
⏱️ 3:06
5.JavaScript Variables - let and const
free
⏱️ 4:50
6.Comments in JavaScript
free
⏱️ 2:55
7.JavaScript Identifer Naming
free
⏱️ 2:52
8.Using TypeScript
free
⏱️ 4:26
9.JavaScript String Masterclass
free
⏱️ 9:29
10.JavaScript Boolean Type
⏱️ 6:45
11.Missing Guide to JavaScript Numbers
⏱️ 15:28
12.JavaScript Objects Demystified
⏱️ 13:33
13.Functions in JavaScript
⏱️ 20:25
14.JavaScript Arrays Masterclass
⏱️ 22:31
15.JavaScript If Else Statements and Best Practices
⏱️ 6:13
16.JavaScript Conditional Expressions
⏱️ 8:38
17.JavaScript Loose vs Strict Equality
⏱️ 4:02
18.Truthy vs Falsy in JavaScript
⏱️ 3:44
19.Concept of JavaScript Nullish and Unification
⏱️ 5:51
20.JavaScript Classes - Object Oriented Programming
⏱️ 10:30
21.JavaScript Error Handling and Exceptions
⏱️ 13:21
22.JavaScript Nullish Operators
⏱️ 5:48
23.JavaScript Switch Statement Masterclass
⏱️ 8:07
24.JavaScript For Loop Iteration Simplified
⏱️ 10:59
25.JSON Masterclass
⏱️ 7:59
26.JavaScript While and Do While Loops
⏱️ 2:52
27.JavaScript Date and Time Simplified
⏱️ 13:16
28.this in JavaScript
⏱️ 12:04
29.JavaScript Tagged Templates Masterclass
⏱️ 5:48
30.Promises in JavaScript
⏱️ 10:01
31.JavaScript Async Await Masterclass
⏱️ 9:00
32.JavaScript Symbols Demystified
⏱️ 7:25
33.JavaScript Iterators and Iterables
⏱️ 8:50
34.JavaScript Generators Simplified
⏱️ 9:17
35.JavaScript Prototype - The Secret Guide
⏱️ 11:21
36.JavaScript Set Builtin Data Structure
⏱️ 9:52
37.JavaScript Map Builtin - HashMap Magic
⏱️ 10:38
38.JavaScript Deferred Promise Pattern - withResolvers
⏱️ 3:35
39.Cloning and Deep Copying in JavaScript
⏱️ 3:14
40.JavaScript Async Await Sequencing and Execution Masterclass
⏱️ 10:31
41.JavaScript Memory Management Masterclass
⏱️ 5:26
42.JavaScript WeakMap Demystified
⏱️ 8:58
43.JavaScript bigint Masterclass
⏱️ 5:35
44.JavaScript WeakSet Explained with Examples
⏱️ 7:47
45.JavaScript Regular Expressions Masterclass
⏱️ 17:54
46.JavaScript Weak References Demystified
⏱️ 5:29
47.JavaScript Memory Leaks Demonstrations and Fixes
⏱️ 6:01
48.Semicolon Free Coding in JavaScript
⏱️ 3:46
49.JavaScript Modules Masterclass
⏱️ 11:36

JavaScript Arrays Masterclass

Subscription Required

You must have an active subscription to access this content.
If you already have a subscription, you can sign in.

Basics

const people = ['Jane', 'Pete'];

console.log(people.length); // 2

console.log(people[0]); // 'Jane'
console.log(people[1]); // 'Pete'

console.log(people[5]); // undefined

people[0] = 'Kim';

console.log(people); // ['Kim', 'Pete']

const empty = [];
const single = ['one'];
const many = ['uno', 'dos', 'tres'];

Mixed Types

const things = [
'Gold',
{ species: 'Cat' },
['Car', 'House']
];

console.log(things[0]); // 'Gold'

console.log(things[1]); // { animal: 'Cat' }
console.log(things[1].species); // 'Cat'

console.log(things[2]); // ['Car', 'House']
console.log(things[2][0]); // 'Car'
console.log(things[2][1]); // 'House'

things[2][1] = 'Home';
console.log(things[2][1]); // 'Home'

Detecting Arrays

const items = ['Pencil', 'Notebook', 'Gum'];
console.log(typeof items); // 'object'

const person = { firstName: 'John', lastName: 'Doe' };
console.log(typeof person); // 'object'

console.log(Array.isArray(items)); // true
console.log(Array.isArray(person)); // false

Methods

pop and push

const items = ['first', 'second'];

items.push('third');
items.push('fourth');

console.log(items); // ['first', 'second', 'third', 'fourth']

console.log(items.pop()); // 'fourth'
console.log(items.pop()); // 'third'

console.log(items); // ['first', 'second']

items.pop(); // 'second'
items.pop(); // 'first'

items.pop(); // undefined

shift and unshift

let items = ['economy', 'deal'];

// Push to the start of the array
items.unshift('business');
items.unshift('vip');
console.log(items); // ['vip', 'business', 'economy', 'deal']

// Pops from the start of the array
console.log(items.shift()); // 'vip'
console.log(items.shift()); // 'business'
console.log(items); // ['economy', 'deal']

console.log(items.shift()); // 'economy'
console.log(items.shift()); // 'deal'

console.log(items.shift()); // undefined

Stack in JavaScript

// LIFO - last in first out - stack
const items = [];

items.push('first');
items.push('second');
items.push('third');

console.log(items.pop()); // 'third'
console.log(items.pop()); // 'second'
console.log(items.pop()); // 'first'

Queue in JavaScript

// FIFO - first in first out - queue
let items = [];

// O(1) - constant time
items.push('first');
items.push('second');
items.push('third');

// O(n) - linear time
console.log(items.shift()); // 'first'
console.log(items.shift()); // 'second'
console.log(items.shift()); // 'third'

Destructuring

const minerals = ['Gold', 'Iron', 'Copper'];

const [first, second] = minerals;
console.log(first, second); // 'Gold', 'Iron'

const [alpha, , gamma] = minerals;
console.log(alpha, gamma); // 'Gold', 'Copper'

const [uno, ...resto] = minerals;
console.log(uno, resto); // 'Gold', ['Iron', 'Copper']
// [...resto, tail] = minerals; // ERROR: rest must be the last element

let [un, duex, trios, quatre] = minerals;
console.log(quatre); // undefined

[un, duex, trios, quatre = 'Silver'] = minerals;
console.log(quatre); // 'Silver'

Spread

let whiteMinerals = ['Silver', 'Platinum'];

let moreMinerals = ['Gold', 'Copper', ...whiteMinerals];
console.log(moreMinerals); // [ 'Gold', 'Copper', 'Silver', 'Platinum' ]

moreMinerals = ['Gold', ...whiteMinerals, 'Copper'];
console.log(moreMinerals); // [ 'Gold', 'Silver', 'Platinum', 'Copper' ]

let yellowMinerals = ['Gold', 'Copper'];
let mostMinerals = ['Iron', ...whiteMinerals, ...yellowMinerals];
console.log(mostMinerals); // [ 'Iron', 'Silver', 'Platinum', 'Gold', 'Copper' ]

Iteration

forEach

let products = [
{ name: 'Apple', price: 100 },
{ name: 'Orange', price: 80 },
{ name: 'Banana', price: 150 },
{ name: 'Melon', price: 200 },
{ name: 'Saffron', price: 2000 },
];

// log all the prices
products.forEach((product) => {
console.log(product.price); // 100, 80, 150, 200, 2000
});

// log as an indexed list
products.forEach((product, index) => {
console.log(index + ': ' + product.name);
});

map

const people = [
{ firstName: 'John', lastName: 'Doe' },
{ firstName: 'Thomas', lastName: 'Calls' },
{ firstName: 'JavaScript', lastName: 'Professional' },
];

const peopleWithFullName = people.map(person => {
return {
...person,
fullName: `${person.firstName} ${person.lastName}`,
};
});

peopleWithFullName
.forEach(person => console.log(person.fullName));

filter

const numbers = [1773, 19, 50, 14, 59];

// get the evens and the odds
//p
const evens = numbers.filter(item => item % 2 === 0);
const odds = numbers.filter(item => item % 2 !== 0);

console.log(evens); // [50, 14]
console.log(odds); // [1773, 19, 59]

Searching JavaScript Arrays

find

const people = [
{ name: 'Percy', born: 1961 },
{ name: 'Wally', born: 1987 },
{ name: 'Harry', born: 1994 },
];

// Find Wally
const wally = people.find(person => person.name === 'Wally');
console.log(wally); // { name: 'Wally', born: 1987 }

// Find Jenny
const jenny = people.find(person => person.name === 'Jenny');
console.log(jenny); // undefined

findIndex

const maybeNumbers = [0, 3, undefined, 5, 6];

maybeNumbers.find(x => x === undefined); // undefined
//p
maybeNumbers.find(x => x === 4); // undefined

const undefinedIndex = maybeNumbers.findIndex(x => x === undefined);
console.log(undefinedIndex); // 2

const fourIndex = maybeNumbers.findIndex(x => x === 4);
console.log(fourIndex); // -1

const valueBeforeUndefined = maybeNumbers[undefinedIndex - 1];
console.log(valueBeforeUndefined); // 3

Array Sub Selection

const animals = ['ant', 'bison', 'camel', 'duck', 'elephant'];

// Everything starting at index 2
console.log(animals.slice(2)); // [ 'camel', 'duck', 'elephant' ]

// Everything starting at index 2, but before index 4
console.log(animals.slice(2, 4)); // [ 'camel', 'duck' ]

// Everything before index 2
console.log(animals.slice(0, 2)); // [ 'ant', 'bison' ]

// Everything
console.log(animals.slice()); // [ 'ant', 'bison', 'camel', 'duck', 'elephant' ]

Boolean Reduction

let products = [
{ name: 'Apple', price: 50 },
{ name: 'Banana', price: 150 },
{ name: 'Melon', price: 200 },
{ name: 'Saffron', price: 2000 },
];

const isExpensive = (product) => product.price > 1000;

const isSomeProductExpensive = products.some(isExpensive);
console.log(isSomeProductExpensive); // true

const isEveryProductExpensive = products.every(isExpensive);
console.log(isEveryProductExpensive); // false

const isSomeProductCheap = products.some(product => product.price < 100); // true
const isEveryProductCheap = products.every(product => product.price < 100); // false

Array reduce

let arr = [1, 2, 3, 4, 5];

let result = arr.reduce((accumulator, current) => accumulator + current, 0);

console.log(result); // 15

result = arr.reduce((sum, current) => sum + current, 0);

const { evenCount, oddCount } = arr.reduce((counts, current) => {
if (current % 2 === 0) {
return { ...counts, evenCount: evenCount + 1 };
} else {
return { ...counts, oddCount: oddCount + 1 };
}
}, { evenCount: 0, oddCount: 0 });

console.log(evenCount, oddCount); // 2 3

Reversing Arrays

const simple = ['alpha', 'beta', 'gamma'];

const simpleReverse = simple.reverse();

console.log(simpleReverse); // ['gamma', 'beta', 'alpha']

console.log(simple); // ['gamma', 'beta', 'alpha']

const better = ['alpha', 'beta', 'gamma'];

const reversedCopy = [...better].reverse();

console.log(reversedCopy); // ['gamma', 'beta', 'alpha']
console.log(better); // ['alpha', 'beta', 'gamma']

Sorting Arrays

let array = ['hello', 'fam'];
array.sort();
console.log(array); // ['fam', 'hello']

array = [1, 3, 22];
array.sort();
console.log(array); // [1, 22, 3]
array = ['1', '3', '22'];
console.log(array.sort()); // ['1', '22', '3']

array = [1, 3, 22];
array.sort((a, b) => a - b);
console.log(array); // [1, 3, 22]
array.sort((b, a) => a - b);
console.log(array); // [22, 3, 1]

Empty Arrays

let items = Array(5);
console.log(items.length); // 5
console.log(items); // [ , , , , ]

items.forEach(x => console.log(x));
// ❌

let oneToFive = items.map((_, index) => index + 1); // ❌
console.log(oneToFive); // [ , , , , ]

items = [...Array(5)];
console.log(items.length); // 5
console.log(items); // [ undefined, undefined, undefined, undefined, undefined ]

items.forEach(x => console.log(x));
// ✅ undefined, undefined, undefined, undefined, undefined

oneToFive = items.map((_, index) => index + 1); // ✅
console.log(oneToFive); // [ 1, 2, 3, 4, 5 ]

items = [...Array(5)]; // ✅
console.log(items); // [ undefined, undefined, undefined, undefined, undefined ]

items = [...Array(5)].map(_ => 0); // [ 0, 0, 0, 0, 0 ]

items = Array(5).fill(0); // ✅
console.log(items); // [ 0, 0, 0, 0, 0 ]

Array Equality

function areArraysEqual(a, b) {
return a.length === b.length && a.every((_, i) => a[i] === b[i]);
}

const itemsA = ['Car', 'TV', 'Remote'];
const itemsB = ['Car', 'TV', 'Remote'];

console.log(itemsA === itemsB); // false

console.log(areArraysEqual(itemsA, itemsB)); // true
javascript
typescript
react
playwright

Enjoy free content straight from your inbox 💌

No spam, unsubscribe at any time.

Transcript

00:00

After object. Literal JavaScript arrays are the second main data structure that we use to create a collection of values. An array can be declared with square brackets containing the individual values separated by a comma. Here we have an array that consists of two items both out of type string, the first one being Jane, and the second one being beat. JavaScript arrays come with the length property that indicates the number of items that are present. For example, hey, we have two people, so people length is going to be the numeric too. We can access the individual items within the array using a square bracket notation and passing in the index for the element that we want to access.

00:37

Like all good programming languages, JavaScript arrays are zero indexed, which means the first element is zero and the second element is index one. Now, if you pass in an index that is actually not present within the array, the JavaScript runtimes gives us that special value that we've talked about before called undefined. Now just like we can read a value using the index rotation, we can write a value to a particular index as well by using an assignment expression. So here we are replacing the first element, which is the element at zero index from Jane to Kim, and now if you log out people again, you can see that it is now updated. We started off with an array that contained two items,

01:13

but of course we can create arrays that have no items, have a single item or as many items as we need. JavaScript arrays are completely un typed and they don't really care about what values you put inside of them. For example, here is an array that contains a string and an object and even un nested array. We can access the individual items as you would expect. For example, things zero is gold and we can continue our selection syntax based on the element that is present at that index. For example, the item at index one is an object and therefore we can access its properties using the dot notation. Similarly, the item at index two is an array,

01:48

which means that we can continue selecting the individual items of the sub array by using further index selections. And of course, in addition to reading, we can use assignment expression as well. For example, here we are replacing the string house with a string home. Now, technically within JavaScript an array is an object, so as an example, if we have an array and we use the type of operator, we get back the literal string object. Now this poses a bit of a problem because this is exactly what is returned for all objects. Fortunately, modern JavaScript has a function built in as a part of the array module called

02:23

is array, which will return to if the variable is an array and for other objects it'll return false arrays, provide methods, push pop shift and unshift to add and remove individual tail and head items, and this allows us to build stacks and cues. So let's take a look at how they work and get some understanding of their runtime complexity. We start off with an array that has two items first and second, and we can push additional items at the end of the array using the built-in push method. This gives us the array containing first, second, third, and fourth. We can remove items from the end of the array by using the corresponding pop

02:59

method, so we get fourth and then third, and now the original array contains just the strings first and second. If you continue to pop, once we run out of the elements, it'll start to return undefined. The time complexity for array methods is based upon how many index need to be changed. So for push and pop, only one index needs to be changed, which is the last element, and therefore the time complexity is O of one or constant time. Now JavaScript methods also provide the opportunity to modify the start of the array. For example, we start with an array consisting of economy and deal and we can push to the start using unshift business and then v i p to give us the array

03:37

v i p business economy deal. JavaScript also provides methods to remove an element from the start of the array called shift, and if you remove the first item, it would give us v i p, then we will get business leaving just economy and deal within the array. Now just like pop, if you continue to shift till we run out of elements, it'll start to give us undefined for shift and unshift and indexes need to be changed as all the items need to be either shifted right for unshift or shifted left for shift and therefore the time complexity for these functions is O of N or linear time.

04:10

So let's take a look at how we can implement stacks and qss and JS script and the impact of these operations. First up, let's implement a last in first out data structure, also called a stack, and we can do this quite easily by using the built-in push method to push items into the array and then pop the individual items from the end of the array so that they come out in last in first out order as we've discussed both push and pop r o f one, so this is actually quite a nice performing stack. Now let's talk about how we can create a first in first out data structure. Also called a queue. For this,

04:42

we would still use push to push the atoms at the end of the array because it performs quite nicely. However, since we need them out in the first in first out fashion, we will shift them out from the front of the array using shift. However, as we've discussed, shift does perform in linear time, so this is not ideal. However, when you are looking for a convenient queue, you can use the built-in JavaScript array for that purpose. JavaScript offers special syntax for destructing arrays that is taking the members of an array and distributing them into different variables. For example, here we have an array consisting of three items, gold, r, n, and copper,

05:17

and we can get the first two items and put them into their individual variables by using the Destructuring syntax, which looks very similar to the structuring or creation syntax except that it is on the other side of the equal sign. This syntax also allows us to skip over an item by using two commas consecutively. For example, here we are skipping over the second member, which is iron. We can also use rest elements to grab all the remaining items and put them into their own array. For example here, the first item, gold is put into Uno and the other two items are put into their own array in the resto variable.

05:51

One thing to be aware of with rest elements is that they must be the last element in the destructuring. If we try to use them before that, we will get an error that it should be the last one. Now we can restructure more elements than they actually are in the array. For example, here we don't have four elements and yet we try to restructure the fourth into qre and of course the DAO script run time in this particular case gives us undefined. Now with Destructuring you can also provide default values and they will kick in whenever the value would've been undefined otherwise. For example, in this particular case, since there is no fourth element,

06:24

it would've been undefined and therefore it is going to default to silver. The modern spread operator that works for JavaScript object literals is also supported for JavaScript arrays. The spread operator can be used to spread the items of one array into another one. For example, here we have some white minerals and then we have some more minerals within which we want to use all the white minerals and we can spread them in. With a triple dot spread operator, you can actually use the spread operator in any portion of the array. For example, here we are putting silver and platinum between gold and copper and you can even use it multiple times. For example, starting with iron,

06:59

we are spreading in the white minerals followed by yellow minerals to get iron, silver, platinum, gold and copper, the spread operator is actually quite useful and it has a number of use cases. For example, it is the recommended modern syntax for combining two arrays. So if you want to combine the white and the yellow minerals, we can spread them both into a new combined array. Now you might recall that push and shift causes a mutation of the original array, so if you want to add an item at the end or the start of an array without mutating the original, you can spread the original into a new array at the required place. Spread can also be used for the simple task of creating a copy of an array to

07:37

prevent accidental mutations to the original. For example, here we create a copy of the white minerals and when we push iron into this copy, the original white minerals remain unchanged. Arrays in JavaScript come with helpful methods that allow us to iterate over all the items in the array, map them to new items and even filter them individually When you want to carry out the same task for all of the items in the array, the built-in for each method saves you from having to write a full fall loop. For example, if you want to log out all of the prices, we can use products four each and then for each product use it within a function

08:12

to log out the product price. The callbacks for all of these iteration methods also take a second optional argument called index, which is the index of the element that we are currently looking at. So for Apple it'll be zero, and for orange it'll be one and so on. And this can actually become really useful if you want to do any sibling analysis beyond the current item. Very similar to the four H method is the built-in map method, which is inspired by functional programming, just like for each map also gets passed in the individual items and its index, but unlike for each, the whole map function returns a new array that contains the results from the

08:47

individual callbacks. So here within the callback for map, we are returning a new object that consists of all of the properties of person along with a new property called full name, which is calculated based on the person first name followed by the person last name. So for each member of people with full name, we will have an object that has a first name, last name as well as a full name and of course you can see the full name being logged to the console. Another iteration method that is built into erase is filter, which can be used to filter only the items that match a particular criteria. For example, from this numbers array,

09:20

we can create separate arrays just for the evens and the odds to create these new arrays. We use the filter method and within the callback we only return two if the number is even or only return two if the number is odd. Now of course, based on the input array, the only even numbers are 50 and 14 and the only odd numbers are 1, 7, 7 3, 19 and 59. It is worth pointing out that in programming lingo functions that return a Boolean based on a past and argument are called a predicate. Therefore, the two functions that we are passing to filter are predicates for even and odd numbers.

09:53

A common task with arrays is to find an item that matches our requirement and JavaScript provides some neat methods for this purpose. For example, consider an array of people with Percy, Wally and Harry and we have the age all task of finding Wally arrays provide a fine method that take a predicate and if this is the item that you are looking for, you simply return true. In our particular case, we want to return true if person name is equal to W, and based on this example, the JavaScript runtime will return the object that contains the name holy born in 1987. Now if the item that we are looking for is not found, for example,

10:28

there is a no person with the name Jenny, then the JavaScript runtime will return that value that we've looked at a hundred times called Undefined. Now this poses a bit of a problem when the item that we are looking for is in itself undefined. For example, if you try to find undefined within this array, we get back undefined, but we can't be sure if we have actually found it because if you search for four as well as an example, we would still get undefined. And in this particular case of course it is because four is not found. So there is an alternative method called find index which returns the index of the found item and there is no ambiguity here because if the item is not found,

11:05

it returns minus one and minus one is not a valid array index. Another use case of the find index function is when you want to use the returned index to look at some of the items, siblings, for example. Here we can see that the item before and defined has the value three. Sometimes you want to take a smaller subsection like a slice of an array as the new array, and for that we have the built-in slice method. Consider a simple array consisting of animals and bison, camel, duck, elephant, and we want to get everything starting in index two, we can use animals slice to get back those items, camel, duck and elephant.

11:40

We can also pass in a second argument to slice to provide the index from where we want to start excluding. For example, hey we want everything starting at index two but before the index four and if you want to start from the beginning but Terminate before a different value, then pass in zero for the starting index and of course provide the second argument of where you want to terminate. Hey, we are grabbing only the first two items and and bison. As a matter of fact, you can actually call slice without any arguments simply to create a copy of the array. One thing to note is that the return array from slice is always a copy and not a reference. As an example, let's take a slice consisting of one element.

12:17

If you push another element into this sliced array, the original array will remain unmodified. The cat is not a part of the original animals. There are some neat methods built into JavaScript arrays that allow us to reduce some collective facts about all of the members of the array consider the array consisting of products, some of which are cheap. For example, apple is only 50 and some of them are really expensive. For example, cron is 2000. For our example, the definition of expensive is anything that is greater than 1000. So we have this predicate that determines if a product's price is going to be

12:51

greater than that. Value arrays have a method called sum which take a predicate function and determine if some of the items within the array match the predicate. If any of the items return true for the past and predicate the sum function resolves to the value. True, and it pretty much reads like standard English for example. Hey, we can say that for the products if something is expensive then is some product expensive should be true, similar to some there is another method called every which basically makes sure that the return value is going to be true for all of the predicates and if it is, then every is going to resolve to true,

13:26

otherwise it is going to resolve to false. You could pretty much read this standard English as well thinking that for the products is everything expensive. In this particular case it isn't, which is why it resolves to false. Now even though we isolated our predicate into its own little function, you don't actually have to do that. You can just pass it. Inline for example is some product cheap. You could just check if any of the products are less than 100, and of course Apple is, which is why this will resolve to true. And similarly we can do that with every as well. Is everything less than 100? No, it is not, which is why it resolves to false.

14:02

One of the most powerful functions built into JavaScript and the bread and butter of functional programming is array reduce. The best way to understand array reduce is with a simple example. So consider this array consisting of five numbers 1, 2, 3, 4, 5, and your mission should choose to accept it is to find the sum for all these numbers. Fundamentally we can do that by starting a sum with the value of a zero, then adding one, then adding two, and so on. And that is exactly what we can do with a simple invocation of array. Reduce. It takes two arguments.

14:33

The first is a reduction function and the second is an initial value for the accumulator. Like we said, we start with an initial sum of zero, which is accumulator, and then for each iteration we get past the accumulator as well as the current item we are looking at and we simply return the sum of the accumulator combined with the current value. So in the next iteration we get an updated accumulator value and the process continues till we run out of items. No surprise, the sum of 1, 2, 3, 4, 5 is 15, which is what we get returned as the final result. Now I want to point out that it is conventional to call the accumulator variable

15:09

the name of the final value that you are trying to accumulate. For example, here we are trying to accumulate the sum, so that is what we would call that parameter. Now even though we used a simple number for this particular accumulator, you can actually use any data type that you want. For example, here we have the accumulator as a simple object consisting of two members, even count and odd count both initialized to zero. Our reduction function in this particular case checks if the current item is even and if it is it increments the even count. Otherwise it increments the odd count. Since our original array, 1, 2, 3, 4, 5 consists of two, even numbers two and four and three,

15:44

your numbers one, three and five. That is the answer that we expect and no surprise when we log out the final results. That is the answer that we get something to be aware of is that certain DWS kit methods are mutating. So in order to use them safely and in a pure functional fashion, you need to create a copy of the array. One example is the built-in reverse method. Consider a simple array consisting of alpha, beta, and gamma and we can invoke the reverse function to reverse the order. So simple reverse is not going to be gamma, beta and alpha, but what you might not expect is that the reverse function is mutating.

16:18

So the original simple array is going to be changed as well, is not going to contain the same reversed order of items that is gamma, beta and alpha. Now the fix is quite simple. We first need to create a copy of the array before we invoke reverse and we already know how to create a copy by using the spread operator. So we spread the better into a new array before invoking reverse. And now the reverse copy is going to be gamma, beta and alpha, but the original better array is going to remain unchanged. JavaScript provides a built-in method for sorting arrays and it does it in end login time, which is the ideal case for comparison based sorting.

16:53

But one thing to be aware of is that if you don't provide this function with a callback, your result might not match what you expected. Consider a simple array consisting of two strings. Hello and fam. Now if we sort this, we get back what you would sort of expect, which is fam first 'cause F comes before edge. Now let's try the sort example again, but this time with the number array consisting of numbers one, three and 22. Now you would expect the sorted result to be in the same ascending order that is one, three and then 22. But what we will actually get is 1 22 and then three.

17:27

Now the reason for this is that the default comparator internally to sort uses string unicode code points, so it works fine if you have strings, they come out in ascending string order but not good. If you have other data types like numbers because this is essentially the same as sorting the strings one, three and 22 and alphabetically two comes before three, so we get 1 22 and then three. Fortunately the sort method takes a compar function, so let's try this example again, but this time passing in our own custom comparator, which basically checks the difference between the two values that we are

18:00

comparing. And if a is going to be bigger than B, then we are going to return a positive number. If they are going to be equal, we are going to return zero and if B is going to be bigger than A, then we are going to return a negative number and this returning of negative zero and positive values to determine if the first item is smaller, equal or bigger than the second is how the comparer function works. So now we get the correctly sorted array, which is one, three, and 22. Now if you want to sort in descending order instead of the default ascending order, my recommendation is to simply replace the order of the parameters to put B

18:34

before A. And this provides a nice visual hint for the next person that you are going in descending order. One common mistake that beginners make when working with JavaScript is unexpectedly using empty arrays that do not actually support the standard array iteration methods. JavaScript provides an array function that is designed to create an array of a particular size. So here we are creating an array consisting of five items. However, by default it creates an array that consists of empty items. So sure this array does have five items, but all of these five items are what are called empty slots.

19:08

These are actually skipped over by array iteration methods. So as an example for each we'll skip over empty slots and we will see no log in this particular case. And similarly, if we try to map these items into another array, like an array of one to five, that will not work either because a map will skip over these slots. The solution to this problem is quite easy. We can use that beautiful spread operator to take this empty slotted array and create a completely filled array. Now of course, those empty slots will be filled by the value which you would expect, which is undefined, but fortunately now we can use the four H loop.

19:42

So we can log out the X values and we will see five undefined. And similarly we can map it into any other thing. For example, we can map it into numbers one to five and that will work as well. Creating MT arrays by using the array function, passing in a number and then spreading it into a new array is the standard approach in modern JavaScript. Now instead of undefined, if you want a filled array, for example, you want an array that consists only of zeros. Of course, we can use the map function to map all of these undefined to the value zero per JavaScript arrays provide another method called fill, which takes the value and fills up all the empty slots as well.

20:17

So if you want an array consisting of undefined, use the spread. And if you want an array consisting of some other value use, the fill arrays are JavaScript objects, which means that they follow the same rules of equality. So even if two arrays might be completely equivalent structurally, unless they point to the same reference, they will not be equal. Here we have two arrays and they both consist of the same primitive strings, which is car, TV, and remote. Every time we use the array literal syntax, we are actually creating a new instance of an array. So items A and items B are completely different arrays, and if we try to use strict equality between them, B will get back the result.

20:53

False. Of course, items A is going to be equal to items A and items B is going to be equal to items B. And similarly, if you create a new variable and point it to the same reference that is contained within items A, then items C is also going to be equal to items A and because items C and items A are pointing to the same array reference, if you push in items into that array using the items C variable and then log out items A, since it's the same array, we can see that camera has been added to that reference items B being a different array is going to remain unchanged. And this is sort of the reason why items A is not equal to items B. Now,

21:29

if you do want to compare to arrays as equal based on their values, we can actually create a utility function for that quite easily. It's really up to you to define what you mean by equality. In our particular case, you want to make sure that both the arrays have the same length and then for every item in array A, the item at that index in array A is strictly equal to the item at that index in array B. So if you go back to that example of two arrays consisting of car, TB and remote, even though they are not strictly equal as far as JavaScript is concerned, the custom function that we wrote are arrays equal will return to for these two

22:04

arrays because they have the same length and the primitive items within the arrays can be compared using strict equality. As you hopefully saw, there is a lot of power built into JavaScript arrays. So even though the original goal for JavaScript was not for it to be a data processing language, it's combined support for objectively tools and arrays makes slicing and dicing data quite enjoyable. As always, thank you for joining me and I will see you in the next one.

Professional Modern JavaScript

Professional Modern JavaScript

1.Course Intro
free
⏱️ 1:13
2.Setup & Tooling
free
⏱️ 3:32
3.Debugger Statements and Breakpoints
free
⏱️ 2:17
4.Primitive Data Types and Values
free
⏱️ 3:06
5.JavaScript Variables - let and const
free
⏱️ 4:50
6.Comments in JavaScript
free
⏱️ 2:55
7.JavaScript Identifer Naming
free
⏱️ 2:52
8.Using TypeScript
free
⏱️ 4:26
9.JavaScript String Masterclass
free
⏱️ 9:29
10.JavaScript Boolean Type
⏱️ 6:45
11.Missing Guide to JavaScript Numbers
⏱️ 15:28
12.JavaScript Objects Demystified
⏱️ 13:33
13.Functions in JavaScript
⏱️ 20:25
14.JavaScript Arrays Masterclass
⏱️ 22:31
15.JavaScript If Else Statements and Best Practices
⏱️ 6:13
16.JavaScript Conditional Expressions
⏱️ 8:38
17.JavaScript Loose vs Strict Equality
⏱️ 4:02
18.Truthy vs Falsy in JavaScript
⏱️ 3:44
19.Concept of JavaScript Nullish and Unification
⏱️ 5:51
20.JavaScript Classes - Object Oriented Programming
⏱️ 10:30
21.JavaScript Error Handling and Exceptions
⏱️ 13:21
22.JavaScript Nullish Operators
⏱️ 5:48
23.JavaScript Switch Statement Masterclass
⏱️ 8:07
24.JavaScript For Loop Iteration Simplified
⏱️ 10:59
25.JSON Masterclass
⏱️ 7:59
26.JavaScript While and Do While Loops
⏱️ 2:52
27.JavaScript Date and Time Simplified
⏱️ 13:16
28.this in JavaScript
⏱️ 12:04
29.JavaScript Tagged Templates Masterclass
⏱️ 5:48
30.Promises in JavaScript
⏱️ 10:01
31.JavaScript Async Await Masterclass
⏱️ 9:00
32.JavaScript Symbols Demystified
⏱️ 7:25
33.JavaScript Iterators and Iterables
⏱️ 8:50
34.JavaScript Generators Simplified
⏱️ 9:17
35.JavaScript Prototype - The Secret Guide
⏱️ 11:21
36.JavaScript Set Builtin Data Structure
⏱️ 9:52
37.JavaScript Map Builtin - HashMap Magic
⏱️ 10:38
38.JavaScript Deferred Promise Pattern - withResolvers
⏱️ 3:35
39.Cloning and Deep Copying in JavaScript
⏱️ 3:14
40.JavaScript Async Await Sequencing and Execution Masterclass
⏱️ 10:31
41.JavaScript Memory Management Masterclass
⏱️ 5:26
42.JavaScript WeakMap Demystified
⏱️ 8:58
43.JavaScript bigint Masterclass
⏱️ 5:35
44.JavaScript WeakSet Explained with Examples
⏱️ 7:47
45.JavaScript Regular Expressions Masterclass
⏱️ 17:54
46.JavaScript Weak References Demystified
⏱️ 5:29
47.JavaScript Memory Leaks Demonstrations and Fixes
⏱️ 6:01
48.Semicolon Free Coding in JavaScript
⏱️ 3:46
49.JavaScript Modules Masterclass
⏱️ 11:36