Lesson 8 of 1910:05 video

JavaScript ES6+ features

The shorter ways modern JavaScript writes everyday code: template literals for strings, destructuring to pull values out of objects and arrays, the three dots of spread and rest (and why a spread copy only goes one level deep), and optional chaining and nullish coalescing for values that might be missing.

In this lesson

  1. 0:00 Intro
  2. 1:05 Template literals
  3. 2:41 Destructuring
  4. 4:36 Three dots
  5. 6:16 Back to the copy
  6. 7:11 Missing values
  7. 9:25 Next time

Transcript

Intro

Here's a rocket: a name, a fuel level, and a crew of three. Make a copy of it, with three dots. Now change the copy. Set its fuel to zero. The original still says eighty. So the copy is a separate object. Now add Zoe to the copy's crew, and look at the original. Zoe is on its crew too. Two changes to the same copy. One stayed in the copy. One reached the original. So what did those three dots copy? Today, we find out.

By the end of this video, you'll understand three things. One: how a template literal builds a string around its values, and how destructuring pulls values out of objects and arrays in one line. Two: what three dots mean in each place they appear, and why that copy shared its crew with the original. Three: two operators, both written with question marks, for values that might not be there.

Template literals

Last time, we built rockets from a class, and found their methods one link up, on the prototype. So far in this series we've written everything the long way: strings joined with plus signs, properties read out one line at a time. JavaScript has shorter ways to write all of that. Most arrived in 2015, in the same update as let, const, arrow functions and classes, and a few came later. None of them lets you do anything new. Each one replaces lines you already know how to write. So for each, we'll write the long version first and then shrink it. Strings first, then pulling values out, then the three dots, then missing values.

Here's a line we've run for two episodes: liftoff with eighty percent fuel. In the code, that one sentence is three pieces joined with plus signs: a string, this dot fuel, and another string. Add the rocket's name, and there are more quotes, more plus signs, and spaces to keep track of inside the strings. A template literal writes it as one piece. Swap the quotes for backticks, the third quote mark from the episode on types. Back then, we said to pick whichever you like. But backticks can do something the other two can't. Inside them, a dollar sign and a pair of curly braces mark a placeholder. Put any expression there, and JavaScript works it out and drops the result into the string. A property. A sum. A function call. Now the code reads the way the sentence prints, with each value in its place.

Destructuring

Next, pulling values out. To work with Kestrel's name and fuel, you copy each one into a variable: const name equals kestrel dot name, const fuel equals kestrel dot fuel. Two lines, and each one says its property twice. Destructuring says it once. Write const, then curly braces holding the property names you want, then an equals sign and the object. JavaScript reads those properties out of Kestrel and makes a variable for each, with the same name. Those braces aren't building an object. On the left of the equals sign they're a pattern: a list of what to take. Ask for a property that isn't there, and its variable is undefined. Or give it a default, the way a parameter gets one, for when the property is missing. Arrays have a pattern too, in square brackets, and it goes by position: const, square brackets, captain, pilot, equals the crew. captain gets the first item, and pilot the second. The names are yours to choose, since an array's items have none.

The place you'll see destructuring most is a function's parameters. Here's a function that takes a rocket and returns a line about it. Five lines: it copies out the name, copies out the fuel, and joins them with plus signs. Now shrink it. A parameter is a variable that gets its value from the call, so the pattern can go right there, in the parentheses. The function still takes one rocket. It unpacks it on the way in, and the two copying lines are gone. Make the string a template literal. Now the body is one expression, so make it an arrow function, and drop the braces and the return. One line, doing the work of five. Same rocket in, same string out. Hand it to map on an array of three rockets, and you get three lines back.

Three dots

Now the three dots. Write them in front of an array, inside the square brackets of a new one, and they mean: put every item of that array here. That's spread syntax. Dot dot dot crew, comma, Zoe, makes a new array of four names, and the crew itself still has three. push would have changed the original. Spread builds a new array. Spread two arrays into the same brackets, and they're joined. The dots work in a call, too, where each item is handed over as a separate argument. And since 2018 they work on objects. Inside curly braces, dot dot dot kestrel copies every property of Kestrel into the new object. Write a property after it, and that one wins: the new rocket has a fuel of a hundred, and Kestrel still has eighty.

The same three dots turn up in one more kind of place, and there they run the other way. Put them in front of a function's last parameter, and that parameter collects every argument that's left, as an array. It's called a rest parameter. launchAll, with dot dot dot ships, takes one rocket, or three, or thirty, and ships is an array of them all. A destructuring pattern can end the same way: captain, then dot dot dot others. captain gets Ada. others gets an array of everyone else. So how does JavaScript know which way the dots run? By where they sit. Where a value is being built, in an array, an object or a call, they spread things out. Where names are being filled, in parameters or a pattern, they gather things in.

Back to the copy

Which brings us back to the copy we started with. Spread made a new object and copied Kestrel's properties into it, one at a time. And each one followed the rule from the arrays episode: a number gets copied, an array gets shared. fuel holds a number. So the copy got an eighty of its own, and setting it to zero touched nothing else. But crew holds an array, and a property, like a variable, doesn't hold the array itself. It holds a link to it. Spread copied the link. Two rockets, two crew properties, one list. Add Zoe through either one, and both show her. A spread copy stops one level down, and everything below that is shared. It's called a shallow copy. When you need every level separate, a built-in function does it: structuredClone. Hand it the rocket, and it copies all the way down.

Missing values

Last group: values that might not be there. Here's a probe. It has a name, a fuel level of zero, and no crew at all. Ask Kestrel how many crew it has: kestrel dot crew dot length. Three. Ask the probe the same way, and the program stops. TypeError: cannot read properties of undefined. probe dot crew is undefined, and undefined has no length to read. You could check with an if before every read. Since 2020 there's a shorter way, called optional chaining. Put a question mark before the dot: probe dot crew, question mark, dot length. The question mark asks about what's on its left. If that's undefined or null, the read stops there, and the answer is undefined. If it's anything else, it works like an ordinary dot. For Kestrel, three. For the probe, undefined, and no error.

Undefined isn't much of an answer, though. For a crew count, you'd rather have zero. So you add a fallback, and for years the tool for that was OR, the two vertical bars from the episode on types. Between any two values, OR hands back the left one, unless JavaScript counts it as false. Then it hands back the right one. Undefined counts as false, and values that do are called falsy. So the missing crew becomes zero. But try it on the fuel: probe dot fuel, OR, the string unknown, for rockets that don't list any. The probe's tank is at zero, and zero is falsy too. So the report says unknown. That's wrong. Zero is a real answer. The same year as optional chaining, JavaScript got an operator that knows the difference: the nullish coalescing operator, two question marks. It falls back to the right side only for null and undefined. Now the probe reports zero, and only a rocket with no fuel listed reports unknown.

Next time

That's modern JavaScript syntax in one line: backticks build a string around its values, destructuring pulls values out by name or by position, three dots spread a list out or gather the rest in, and two question-mark operators cover what's missing. Next time, we look at what happens when a program goes wrong: how to read an error, how to throw one of your own, and how to catch one before it stops everything.

Learn more