Lesson 5 of 199:52 video

JavaScript arrays and objects

How arrays hold a list and objects hold values by name, how they nest, why two variables can share one object and a const object can still change, how forEach, map, filter and reduce work through a list with a callback, and why sort puts 10 before 2 until you hand it one.

In this lesson

  1. 0:00 Intro
  2. 0:59 Many values, one name
  3. 2:27 Objects
  4. 4:31 Changing them
  5. 6:42 Callbacks over lists
  6. 8:06 Back to the hook
  7. 9:16 Next time

Transcript

Intro

Here's a list of four numbers: three, ten, one, two. Ask JavaScript to sort it, and you get one, ten, two, three. Ten, filed between one and two. No error, no warning. Now ask it to sort a list of names, and they come out in perfect alphabetical order. So JavaScript can sort. Why does it think ten comes before two? Today, we find out.

By the end of this video, you'll understand three things. One: how arrays and objects hold many values under one name, and how you get each one back out. Two: why two variables can share one object, and why a const object can still change. Three: how the callbacks from last time work through a whole list in one line, and what sort was doing with that ten.

Many values, one name

Last time, we went inside functions, and ended with functions that take functions. Every value we've used so far has been a single thing: one number, one string, one true or false. Real programs carry more than that: a crew of three, a rocket with a name, a stage count and a fuel level, a whole fleet of rockets. JavaScript gives you two containers for that. An array holds a list, in order. An object holds values by name. Both are values themselves, so they go in variables, in parameters, and inside each other. We'll build a rocket's worth of them, see what makes them different from every value before, and then let last episode's callbacks loose on them.

An array is a list, written in square brackets with commas between the values. Here's the crew: three strings, in order. The whole list is one value, so it fits in one variable. To get an item back, write the variable and then square brackets with the item's position. Positions start at zero, not one. So crew zero is Ada, and the third name, Omar, is at position two. That position is called an index. Every array knows its own length: three here. Ask for an index that isn't there, like three, and you get undefined. No error, just undefined, like the missing argument last time.

Objects

An object holds values by name instead of position. Curly braces, and inside, pairs: a name, a colon, a value, with commas between. Each pair is a property. Here's a rocket: a name, a stage count and a fuel level. To read one, write the object, a dot and the property's name. Assign to it, and the value changes. Assign to a name the object doesn't have, and the property is created on the spot. Read a name it doesn't have, and you get undefined, same as the array. An array is for things you'd count. An object is for things you'd label.

There's a second way to read a property: square brackets, with the name as a string inside. Same property, same value. Why two ways? The dot needs the name spelled out in the code. The brackets take any expression, so the name can come from a variable. Read key with a dot, and JavaScript looks for a property called key: undefined. Read it with brackets, and it looks up fuel: eighty. Brackets also take names a dot can't handle, like one with a space in it. And that explains the array's square brackets. An array is really an object, with the positions, zero, one, two, as its property names, and length as one more. Ask type of an array, and the answer is object.

A property can hold any value at all, and so can a slot in a list. So they nest. Give the rocket a crew property holding the crew array, and rocket dot crew, bracket zero, is Ada: read it left to right, one step at a time. Turn it around, put objects in an array, and you have a fleet: a list of rockets, each with its own name, fuel and stage count. Fleet one dot name is Heron. This shape, a list of records, is most of the data you'll ever touch. Products in a store, messages in a chat, search results: all arrays of objects.

Changing them

We've changed the rocket already. Arrays change too. Assign to an index, and that item is replaced. push adds an item at the end, and hands back the new length. pop takes the last item off, and hands you that item. includes asks whether something is in the list at all: true or false. Notice the shape of those three: the value, a dot, and a function. A function kept in a property is a method, and the value it belongs to is what it works on. Arrays come with dozens. You've used one since the start: log is a method of console.

Here's the part that trips people up. Put a hundred in fuel, copy fuel into spare, and set spare to fifty. fuel is still a hundred: the number was copied. Now look at the rocket's crew. We gave it the crew array before we changed anything, and we never touched rocket dot crew. Yet Lee is there. There aren't two lists. There's one list, with two names. A variable doesn't hold an object or an array itself. It holds a link to it, the way last episode's closure held a link to its variable. Copy the variable and you copy the link, so both names lead to the same place, and a change through either one shows up through both. A number, a string or a boolean gets copied. An object or an array gets shared.

Two things follow. First, rocket is a const, and we've been changing it all episode. const locks the variable, not the value. The name can't be pointed at a different object, but the object it points at can change freely. Assign a new object to rocket and you get a TypeError. Change its fuel and JavaScript doesn't mind. Second, equality. Two objects written exactly the same, compared with triple equals, are not equal. The comparison asks whether both links lead to the same object, not whether the contents match. The only object equal to a rocket is that same rocket. To compare contents, you compare them property by property, yourself.

Callbacks over lists

Now the callbacks. To do something with every item, you could write a for loop from zero to length, like last time's countdown. Since 2015 there's for of, which hands you each item in turn, no index needed. And arrays have a third way, built on last episode's idea. forEach takes a function and calls it once per item, with the item as the argument. The loop is inside JavaScript, and what happens each round comes from you. map goes one step further. It calls your function on every item and gathers the results in a new array. Hand it an arrow that reads the name, and three rockets become three names. The fleet itself isn't changed.

filter keeps the items your function says yes to. Fuel above fifty? Kestrel and Osprey, in a new array, and Heron is left behind. reduce boils a whole list down to one value. Its function takes two things, the running total and the current item, and after the function comes the starting value, zero. Each round, whatever your function returns becomes the total for the next round, and after the last item, that total is the answer: two hundred and fifteen. Each of these took a one-line arrow and did the looping for you. This is how most real JavaScript works through data: not with a loop you write, but with a function you hand over.

Back to the hook

Which brings us back to the hook. sort is one of these methods, and it takes a callback too, but it works without one. Then it has to compare the items somehow, so it turns each one into a string and compares the strings, one character at a time, the way a dictionary would. For names, that's exactly right. For numbers, it's a trap: the string ten starts with a one, one comes before two, so ten is filed before two. The fix is the callback. Give sort a function that takes two items and returns a number: negative if the first belongs first, positive if the second does, zero if it doesn't matter. For numbers, that's the first minus the second, and the list comes out one, two, three, ten. One last thing. sort rearranges the array itself, unlike map and filter, which hand you a new one. Since 2023 there's toSorted, which sorts a copy and leaves the original alone.

Next time

That's arrays and objects in one line: arrays hold a list by position, objects hold values by name, a variable holds a link to them rather than a copy, and the array methods let a callback do the looping. Next time, we put functions inside objects, as methods, and meet the word this, which means whatever is left of the dot.

Learn more