Loading

T5 Modern JavaScript (ES6 and later) · Lesson 3

Destructuring and spread

Unpacking arrays and objects into names in one line, with defaults and new names; unpacking in parameters and in loops over Object.entries; gathering the rest with three dots; spreading arrays into calls and new arrays; and copying and updating objects without changing the original.

  • unpack an array into names, skipping items and giving defaults
  • unpack an object's properties, renaming them and reaching inside nested objects
  • unpack in a function's parameters and in a for...of loop over Object.entries
  • gather the remaining items or properties with a rest element, and any number of arguments with a rest parameter
  • spread an array into a call or a new array, and copy an array
  • copy and update an object with object spread, knowing that the copy is shallow
About 60 minutesChecked against Node.js on the laptop (the kit runs every code block with it) 22.23.1 (2026-11-06); Google Chrome on the laptop (the kit renders every HTML block in it, and the DevTools step describes its panels) 155 (2026-11-06)Play this lesson's games

The back cover

Data arrives in bundles: an array of the day's winners, an object for a shop with a dozen properties. Most code needs only a few of those values, each under its own name. Destructuring takes them out in one line, and spread lays values out where many are wanted.

These pages show how to unpack an array by position and an object by name, with defaults and new names. They show patterns in parameters and in loops, and how three dots gather the rest. They show spread in calls and in new arrays, and how to copy and update an object without changing the original.

Before you start

The story: Two faces, one tune

The Clock Tower has two faces, north and south, and each has its own settings: the hour it first strikes, its volume, and the raga it chimes. Last week a clockmaker set up the south face. To save time, the script gave the south face the north face's settings, and then changed the south face's raga to Yaman.

Since then both faces chime Yaman, and the market on the north side has lost its morning Bhairav.

Master Hakim Verge listens to the two faces ring the same notes. "Nobody touched the north face," he says. "Yet it changed. When two names hold one object, they hold one tune. Find out how to give a face settings of its own."

Programs pass data around in arrays and objects, and most lines that use them take something out or put something together. Taking out the name, the city and the phone of a customer used to cost three lines. Making a copy of a settings object with one value changed needed a helper. Modern JavaScript has a short syntax for both: destructuring takes values out, and three dots, spread, puts them together.

It builds on these ideas. Each one has a tiny example, so you can check that you remember it.

What you already knowA tiny exampleWhere it comes back
Arrays and indexes.list[0] is the first item.Unpacking by position.
Objects and properties.shop.nameUnpacking by name.
Shorthand properties.{ name } means { name: name }.Patterns look the same, on the other side of =.
Default parameters.function greet(name = "Guest")Defaults inside patterns.
Object.entries.[key, value] pairs.Unpacked in a for...of loop.
for...of.for (const item of items)A pattern in place of the name.
References.const y = x shares one object.Why a real copy is needed.
Shallow and deep copies.Object.assign({}, o) and structuredClone(o)Spread makes a shallow copy.
The rest parameter.function tag(strings, ...values)Gathering any number of arguments.
Math.max.Math.max(3, 9, 4) is 9.Spreading an array into a call.

By the end of this lesson you will be able to:

  • unpack an array into names, skipping items and giving defaults;
  • unpack an object's properties, renaming them and reaching inside nested objects;
  • unpack in a function's parameters and in a for...of loop over Object.entries;
  • gather the remaining items or properties with a rest element, and any number of arguments with a rest parameter;
  • spread an array into a call or a new array, and copy an array;
  • copy and update an object with object spread, knowing that the copy is shallow.

How to follow this lesson

Every pattern in this lesson is a picture of the data it unpacks. Before you read a pattern, look at the shape of the array or object on the right of the =, then match the two side by side.

In one line

Destructuring takes values out of arrays and objects into names, and the three dots gather or spread them; this lesson shows both, with their traps.

Unpacking an array

At a glance

A school's sports day sorts the 100 m runners by time, and the first three names are the winners. The old way to name them takes three lines, one index each: winners[0], winners[1], winners[2].

Destructuring does it in one: const [gold, silver, bronze] = winners; names the items by position. No index is written at all. An empty place between commas skips an item, a missing item gives undefined, and a default after = fills the gap. Two names can even swap their values in one line: [a, b] = [b, a].

Take a guess: Can the square brackets unpack a Set or a string, or only an array?

A school's sports day sorts the 100 m runners by time. The first three names are the winners. The old way to name them takes three lines, one index each:

const finishers = ["Asha", "Ravi", "Meera", "Kabir"];
const gold = finishers[0];
const silver = finishers[1];
const bronze = finishers[2];
console.log(gold, silver, bronze);
Asha Ravi Meera

Destructuring writes the same thing as one line. On the left of the =, square brackets hold names instead of values; each name takes the item at its position:

Destructuring

Writing a pattern on the left of = that has the shape of an array or an object, so that each name in the pattern takes the matching value: const [a, b] = list; makes a from list[0] and b from list[1].

const finishers = ["Asha", "Ravi", "Meera", "Kabir"];
const [gold, silver, bronze] = finishers;
console.log(gold, silver, bronze);
Asha Ravi Meera

Read the pattern as a picture: the array has a first, a second and a third place, and the pattern names them. The fourth place has no name in the pattern, so Kabir is left out; the array itself is not changed. The brackets on the left do not make an array. They describe one.

Skipping, missing items and defaults

Leave a place empty, between two commas, to skip an item:

const [a, , c] = [10, 20, 30];
console.log(a, c);
10 30

A name with no item at its place gets undefined, just as list[5] would. No error is raised:

const [x, y, z] = [1, 2];
console.log(x, y, z);
1 2 undefined

A default, written after an = inside the pattern, is used when the item is missing, exactly like a default parameter:

const [p = 5, q = 7] = [1];
console.log(p, q);
1 7

p found the item 1, so its default was not needed. q found nothing, so it took its default, 7.

Two tricks that come up often

Swapping two names needs no third name. The right side builds a new array of the two values in the other order, and the pattern unpacks it:

let left = "tea";
let right = "coffee";
[left, right] = [right, left];
console.log(left, right);
coffee tea

And a function can return two answers as an array, which the caller unpacks into two names:

function lowHigh(list) {
  const sorted = list.toSorted((a, b) => a - b);
  return [sorted[0], sorted[sorted.length - 1]];
}
const [low, high] = lowHigh([40, 15, 80]);
console.log(low, high);
15 80

Worked example 1

A bus app gets each stop as an array of three items: the stop's name, its arrival time and its platform. Some stops have no platform. Unpack a stop into names, with the platform 1 when none is given.

What we have: two stops, one with a platform and one without

What we need: the name, time and platform of each, with a default platform

The plan: unpack each stop with a pattern of three names, giving the platform a default of 1

const stopA = ["Shivajinagar", "8.10", 3];
const stopB = ["Swargate", "8.40"];
const [nameA, timeA, platformA = 1] = stopA;
const [nameB, timeB, platformB = 1] = stopB;
console.log(`${nameA} ${timeA} platform ${platformA}`);
console.log(`${nameB} ${timeB} platform ${platformB}`);
Shivajinagar 8.10 platform 3
Swargate 8.40 platform 1

Shivajinagar is on platform 3, and Swargate on the default platform 1.

Check: stopA had a third item, so its default was not used; stopB had none.

A path that fails: writing the platform as stop[2] || 1 in every line that needs it. It works, but the rule is repeated wherever the platform is used, and a platform 0 would wrongly become 1.

When you are stuck: an unpacked name has the wrong value

Count the positions: the first name takes item 0, the second item 1, and so on.

An empty place between commas skips an item; a missing comma shifts every name after it.

undefined means the array had no item at that place: give a default, or check the data.

Print the array itself first, to see its real shape.

Your turn

const [first, , third = "none", fourth = "none"] = ["a", "b", "c"];
console.log(first, third, fourth);
What does this print? Say your answer aloud first, then press Run or tap to reveal.Tap to reveal
a c none
  1. first takes a; the empty place skips b.
  2. third finds c, so its default is not used.
  3. fourth finds nothing, so it takes none.

It prints a c none.

What do you write to swap the values of two let names, a and b?Tap to reveal
  1. Build the values in the other order on the right, and unpack them on the left.

[a, b] = [b, a];

What does const [x] = []; give x?Tap to reveal
  1. The array has no first item.
  2. A missing item gives undefined, with no error.

undefined.

Did you know?

Swapping, as Python does

Swapping two values in one line is an old idea. In the first program of Python's own tutorial, a multiple assignment gives two variables new values at once, and the tutorial notes that the right-hand side is all evaluated first, before any assignment takes place. JavaScript's [a, b] = [b, a] works the same way: the array on the right is built before either name changes.

Why it fits here: It explains why this topic's swap needs no spare variable: the new array on the right is complete before any name changes.

Source: Python documentation: An Informal Introduction to Python

Any iterable will do

The square brackets work on more than arrays. MDN explains that array destructuring calls the iterable protocol of whatever stands on the right. So any iterable can be unpacked: a Map gives its pairs, a Set its members, a string its letters. javascript.info shows the string case, with three letters from abc. A plain object is not iterable, and cannot be unpacked with square brackets.

Why it fits here: It answers this topic's question: square brackets unpack anything that can be stepped through, not only arrays.

Sources: MDN: Destructuring; javascript.info: Destructuring assignment

In one line

const [a, b] = list; names the items of an array by position. An empty place skips an item, a missing item gives undefined, and a default after = fills it. Swap with [a, b] = [b, a].

Unpacking an object

At a glance

Objects are unpacked the same way, with curly braces instead of square brackets. An array is matched by position; an object is matched by name, so the order of the names does not matter.

const { name, city } = shop; makes two names from the two properties. A colon renames, so { name: shopName } makes shopName. An = gives a default when the property is missing or undefined, and a nested pattern reaches inside an inner object. Each name must match a property's spelling exactly, capitals included.

Take a guess: Why does { a, b } = obj fail on a line of its own, when const { a, b } = obj works?

Objects are unpacked the same way, with curly braces instead of square brackets. An array is matched by position; an object is matched by name. Each name in the pattern takes the property with the same name:

const shop = { name: "Ravi Stores", city: "Pune", open: true };
const { name, city } = shop;
console.log(name, city);
Ravi Stores Pune

The order inside the braces does not matter, and the pattern may name as few properties as you need. const { city, name } = shop; gives the same two names, and open is left out. This line is the same as writing const name = shop.name; and const city = shop.city;, in one line.

A new name, and a default

Sometimes the property's name is not the name you want, perhaps because a name of that name already exists. Write the property, a colon, and the new name. A default is written after an =, as in arrays:

const shop = { name: "Ravi Stores" };
const { name: shopName, phone = "not given" } = shop;
console.log(shopName, phone);
Ravi Stores not given

Read name: shopName as "take the property name, and call it shopName". The colon points from where the value comes to where it goes. No name called name was made; only shopName. The shop has no phone property, so phone takes its default.

A default is used only for a value that is missing or undefined. A property that holds null is a real value, so its default is not used:

const { a = 1, b = 2 } = { a: null, b: undefined };
console.log(a, b);
null 2
PatternMeansExample
{ name }take name, call it nameRavi Stores
{ name: shopName }take name, call it shopNameRavi Stores
{ phone = "not given" }take phone, or the default if it is missingnot given
{ phone: tel = "none" }take phone, call it tel, with a defaultnone

Reaching inside a nested object

A pattern can follow the shape of the data deeper. Where a property holds an object, write a pattern for that object after its colon:

const order = { id: 77, customer: { name: "Asha", city: "Nagpur" } };
const { id, customer: { city } } = order;
console.log(id, city);
77 Nagpur

Here customer: { city } means "go into customer, and take city from there". It does not make a name called customer. Only the names at the ends of the pattern are made:

const order = { id: 77, customer: { name: "Asha", city: "Nagpur" } };
const { customer: { city } } = order;
console.log(typeof customer);
undefined

Nesting deeper than two levels makes a pattern hard to read. When the data is deep, unpack one level at a time, in two short lines.

Unpacking into names that already exist

Without const or let, a pattern assigns to names made earlier. For an object pattern, the whole statement must then be wrapped in round brackets, because a line that starts with a brace is read as a block of code:

let a, b;
({ a, b } = { a: 1, b: 2 });
console.log(a, b);
1 2

Worked example 2

An app for train times gets each train as an object. Show the train's number and name, and where and when it departs, which sit inside a departs object. Some trains have no pantry car; show no pantry for those.

What we have: a train object with a nested departs object, and no pantry property

What we need: the number, the name, the station, the time and the pantry

The plan: unpack the top level, reach into departs with a nested pattern, and give pantry a default

const train = { number: 101, name: "Morning Express", departs: { station: "Pune", time: "6.15" } };
const { number, name, departs: { station, time }, pantry = "no pantry" } = train;
console.log(`${number} ${name}: ${station} at ${time}, ${pantry}`);
101 Morning Express: Pune at 6.15, no pantry

It shows 101 Morning Express: Pune at 6.15, no pantry.

Check: station and time came from inside departs, and pantry took its default.

A path that fails: writing train.departs.station and train.departs.time in every line of a long function. It works, but the long paths repeat, and a slip in one of them gives undefined silently.

When you are stuck: an object pattern gives undefined

Check the spelling: a pattern name must match the property's name exactly, capitals included.

With a colon, the name on the right is the new one: { name: shopName } makes shopName, not name.

A nested pattern makes only the inner names; the outer property is not a name.

A default is not used for null, only for a missing property or undefined.

Your turn

const user = { first: "Asha", city: undefined };
const { first: given, city = "Pune", age = 15 } = user;
console.log(given, city, age);
What does this print? Say your answer aloud first, then press Run or tap to reveal.Tap to reveal
Asha Pune 15
  1. first is renamed given: Asha.
  2. city is undefined, so its default Pune is used.
  3. age is missing, so its default 15 is used.

It prints Asha Pune 15.

Write a pattern that takes the property title of book and calls it heading.Tap to reveal
  1. The property comes first, then a colon, then the new name.

const { title: heading } = book;

Why does { a, b } = obj; fail at the start of a line, when a and b already exist?Tap to reveal
  1. A line that starts with a brace is read as a block of code.

Because it must be written ({ a, b } = obj);, in round brackets.

Did you know?

Braces that look like a block

An object pattern needs care when no const or let comes before it. MDN explains that { a, b } = obj on a line of its own is not valid, because the braces are read as a block, not as an object. The standard forbids an expression statement from starting with a brace. Wrapped in round brackets, ({ a, b } = obj) works.

Why it fits here: It warns about this topic's object patterns: with no const or let in front, the whole assignment needs round brackets.

Sources: MDN: Destructuring; ECMAScript Language Specification: Expression Statement

A name from the prototype

Unpacking reads a property the way a dot does, so it can find names that an object only inherits. MDN notes that when an object does not have a property itself, the lookup continues along the prototype chain. So const { toString } = {} gives a function, though the empty object has no properties of its own. The standard's steps read each name with GetV, an ordinary property lookup.

Why it fits here: It warns about this topic's object patterns: a name can come back filled from the object's prototype, not from the object itself.

Sources: MDN: Destructuring; ECMAScript Language Specification: Runtime Semantics: KeyedBindingInitialization

In one line

const { name, city } = shop; takes properties by name, in any order. A colon renames (name: shopName), an = gives a default for missing or undefined values, and a nested pattern reaches inside an inner object.

Unpacking in parameters and loops

At a glance

Patterns work anywhere JavaScript makes a name for you. Two of those places are used all the time: a function's parameters, and the name in a for...of loop.

A parameter can be a pattern, so a function names exactly the properties it uses, with defaults if it likes. Writing = {} after the pattern lets the function be called with nothing at all. In a for...of over Object.entries(obj), the pattern [key, value] unpacks each pair as it arrives. The function's first line then shows what it needs.

Take a guess: How can a JavaScript call name its arguments, as Python's keyword arguments do?

Patterns work anywhere JavaScript makes a name for you, and two of those places are used all the time: a function's parameters, and the name of a for...of loop.

A pattern as a parameter

When a function receives an object, its parameter can be a pattern. The function then names exactly the properties it uses, with defaults if it likes:

function greet({ name, city = "Pune" }) {
  return `${name} from ${city}`;
}
console.log(greet({ name: "Asha" }), greet({ name: "Ravi", city: "Goa" }));
Asha from Pune Ravi from Goa

This is a common way to write a function with many settings, called an options object. The caller writes each setting by name, so the order does not matter, a setting can be left out, and a reader of the call sees what every value means. Compare book("Pune", "Goa", 2, true) with book({ from: "Pune", to: "Goa", seats: 2, window: true }): only the second says what 2 and true are.

One trap comes with it. If the function is called with no argument at all, the pattern tries to unpack undefined, which is an error:

function greet({ name }) {
  return name;
}
greet();
Uncaught TypeError: Cannot destructure property 'name' of 'undefined' as it is undefined.
    at greet (line 1)
    at line 4

The cure is a default for the whole parameter: an empty object, written = {} after the pattern. A call with nothing then unpacks the empty object, and every name gets its own default or undefined:

function greet({ name } = {}) {
  return name ?? "Guest";
}
console.log(greet());
Guest

A pattern in a loop

The objects lesson showed that Object.entries turns an object into an array of [key, value] pairs. Each pair is a small array, so a for...of loop can unpack it into two names on the spot:

const marks = { maths: 88, science: 92 };
for (const [subject, mark] of Object.entries(marks)) {
  console.log(`${subject}: ${mark}`);
}
maths: 88
science: 92

Without the pattern, the loop would hold each pair as one name, and the body would need pair[0] and pair[1], which say nothing about what they are. The pattern names them subject and mark.

The same works for an array of objects: an object pattern in place of the loop's name, or in an arrow's parameter:

const items = [{ name: "Tea", price: 15 }, { name: "Dosa", price: 80 }];
for (const { name, price } of items) {
  console.log(name, price);
}
console.log(items.map(({ name }) => name));
Tea 15
Dosa 80
[ 'Tea', 'Dosa' ]

An arrow whose parameter is a pattern needs round brackets around it, ({ name }) => name, even though it has one parameter.

Worked example 3

A cab app's function prices a ride from an options object: the kilometres, a rate of ₹15 a kilometre unless another is given, and a night charge of ₹50 when night is true. Write it so that a call with only the kilometres works, and a call with nothing gives 0.

What we have: an options object with km, rate and night, where only km is usually given

What we need: the fare in rupees

The plan: make the parameter a pattern with defaults for every setting, and = {} for a call with nothing

function fare({ km = 0, rate = 15, night = false } = {}) {
  return km * rate + (night ? 50 : 0);
}
console.log(fare({ km: 10 }), fare({ km: 10, night: true }), fare({ km: 4, rate: 20 }), fare());
150 200 80 0
  1. Each call names only what differs from the defaults. 10 km at ₹15 is 150; at night 50 more, 200; 4 km at ₹20 is 80; no ride at all is 0.

The fares are ₹150, ₹200, ₹80 and ₹0.

Check: 10 × 15 = 150, 150 + 50 = 200, 4 × 20 = 80.

A path that fails: three ordinary parameters, fare(km, rate, night). A night ride at the normal rate must then be written fare(10, undefined, true), and a reader cannot tell what true means.

When you are stuck: a destructured parameter fails

Cannot destructure property ... of 'undefined' means the function was called without the object: add = {} after the pattern.

Check that the caller passes an object, and not the values one by one.

Wrap a pattern parameter of an arrow in round brackets: ({ name }) => name.

Print the argument at the top of the function to see its real shape.

Your turn

function show({ size = 2, colour = "blue" } = {}) {
  return `${size} ${colour}`;
}
console.log(show({ colour: "red" }), show());
What does this print? Say your answer aloud first, then press Run or tap to reveal.Tap to reveal
2 red 2 blue
  1. The first call gives only colour, so size takes its default.
  2. The second call gives nothing: = {} makes both take their defaults.

It prints 2 red 2 blue.

Write a for...of loop over Object.entries(stock) that names each key item and each value count.Tap to reveal
  1. Each entry is a [key, value] array, so unpack it with an array pattern.

for (const [item, count] of Object.entries(stock)) { ... }

Why is book({ from: "Pune", seats: 2 }) easier to read than book("Pune", 2)?Tap to reveal
  1. Each value in the options object has its name beside it.

Because every value says what it is, and any setting can be left out.

Did you know?

Named arguments, JavaScript style

Some languages let a call name its arguments. Python's tutorial shows functions called with keyword arguments of the form kwarg=value, in any order. A destructured parameter gives JavaScript the same effect: book({ seats: 2, train: "Rajdhani" }) names each value, the order no longer matters, and a value left out takes its default.

Why it fits here: It answers this topic's question: one object, unpacked in the parameter, lets a JavaScript call name its arguments.

Sources: Python documentation: More Control Flow Tools; MDN: Destructuring

Every React component does this

React's components are written with this topic's patterns. React's own guide declares a component as function Avatar({ person, size }) and explains that this syntax is called destructuring, equivalent to reading properties from a function parameter. A default works the same way inside the pattern: size = 100 gives a size whenever none is passed.

Why it fits here: It shows this topic's parameter patterns in a library used on a great many sites: every component unpacks its props this way.

Source: React: Passing Props to a Component

In one line

A parameter can be a pattern: the function names the properties it uses, with defaults, and = {} lets it be called with nothing. In a for...of over Object.entries, [key, value] unpacks each pair.

Gathering the rest

At a glance

A pattern names some values, and often you want a few of them by name and everything else kept together. Three dots before the last name of a pattern gather what is left.

In an array pattern the rest becomes a new array; in an object pattern, a new object without the properties already named. The original is left as it was. A rest parameter gathers the remaining arguments of a call into an array, which is empty when there are none, never undefined.

Take a guess: Can anything come after the three dots in a pattern?

A pattern names some values. Often you want a few of them by name and everything else kept together. Three dots before the last name of a pattern gather all the remaining items into it.

Rest element

The last name of a pattern written with three dots before it, ...rest. It gathers every item or property that the other names did not take: into a new array for an array pattern, into a new object for an object pattern.

const [head, ...tail] = [1, 2, 3, 4];
console.log(head, tail);
1 [ 2, 3, 4 ]

head takes the first item, and tail gathers the other three into a new array. With an object pattern, the rest is a new object holding every property not named:

const { id, ...details } = { id: 7, name: "Tea", price: 15 };
console.log(id, details);
7 { name: 'Tea', price: 15 }

This is a neat way to remove a property without touching the original. The user below keeps both properties; others is a new object without name:

const user = { name: "Asha", age: 15 };
const { name, ...others } = user;
console.log(others, user);
{ age: 15 } { name: 'Asha', age: 15 }

The rest must be the last thing in the pattern, because it takes everything after the other names. Nothing may follow it, not even a comma:

const [a, ...b,] = [1, 2, 3];
Uncaught SyntaxError: Rest element must be last element

Rest parameters

The template literals lesson met the same three dots in a function's parameters. A rest parameter gathers all the remaining arguments of a call into an array, however many there are, even none:

function total(...prices) {
  return prices.reduce((sum, p) => sum + p, 0);
}
console.log(total(15, 80, 40), total());
135 0

With no arguments, prices is an empty array, so the total is the reduce's starting value, 0. A rest parameter comes after the ordinary ones, and there can be only one, at the end, for the same reason as in a pattern.

Worked example 4

A delivery app plans a route: a start, then any number of stops. Write route(start, ...stops), which says where the route starts, how many stops it has, and what they are.

What we have: a start and a list of stops of any length

What we need: one line, such as Pune, then 2 stops: Lonavala, Khopoli

The plan: name the start as an ordinary parameter, gather the stops with a rest parameter, and use its length and join

function route(start, ...stops) {
  return `${start}, then ${stops.length} stops: ${stops.join(", ")}`;
}
console.log(route("Pune", "Lonavala", "Khopoli"));
console.log(route("Nagpur", "Wardha"));
Pune, then 2 stops: Lonavala, Khopoli
Nagpur, then 1 stops: Wardha

The first route has 2 stops, the second 1.

Check: the start is not counted among the stops, because it was taken by the first parameter.

A path that fails: passing the stops as one array, route("Pune", ["Lonavala", "Khopoli"]), to a function that expects them one by one. stops is then an array holding one array, and its length is 1.

1 stops

The second line reads 1 stops, which is wrong English. A real app chooses the word from the count, for example with a ternary in the gap: stops.length === 1 ? "stop" : "stops".

When you are stuck: the rest holds the wrong things

The rest takes only what the names before it did not; count the names before it.

A rest element must be last: nothing, not even a comma, may follow it.

A rest parameter is always an array, empty when no arguments are left.

If the rest holds one array inside an array, the caller passed an array instead of separate values.

Your turn

const [first, ...others] = ["x"];
const { a, ...more } = { a: 1 };
console.log(first, others, more);
What does this print? Say your answer aloud first, then press Run or tap to reveal.Tap to reveal
x [] {}
  1. first takes x, and nothing is left: an empty array.
  2. a takes 1, and no property is left: an empty object.

It prints x [] {}.

Write a function count(...items) that returns how many arguments it was given.Tap to reveal
function count(...items) {
  return items.length;
}
console.log(count("a", "b", "c"), count());
3 0

items.length gives 3 and 0.

How do you make a copy of settings without its token property, leaving settings unchanged?Tap to reveal
  1. Name token in an object pattern, and gather the rest.

const { token, ...safe } = settings;: safe is the copy.

Did you know?

Rest goes last

The three dots must come last. MDN warns that the rest element must be the last in the pattern, and must not even have a trailing comma after it. So [a, ...b,] is a SyntaxError, whose message says that a rest element may not have a trailing comma. A rest element takes everything that is left, so nothing could ever come after it.

Why it fits here: It answers this topic's question: nothing may follow the dots, not even a comma, because the rest takes all that remains.

Sources: MDN: Destructuring; ECMAScript 2018 Language Specification

Objects waited three years

Rest and spread worked on arrays in ES2015, but on objects only later. TC39's list of finished proposals names Rest/Spread Properties, championed by Sebastian Markbåge, and the 2018 edition of the standard defines CopyDataProperties, the step that copies an object's properties while leaving out the ones already named. So { a, ...others } is a younger feature than [a, ...others].

Why it fits here: It dates this topic's object rest: the three dots reached objects in 2018, three years after arrays.

Sources: TC39: Finished Proposals; ECMAScript 2018 Language Specification

In one line

Three dots before the last name of a pattern gather what is left: a new array, or a new object without the named properties. A rest parameter gathers the remaining arguments into an array, empty if there are none.

Spreading values out

At a glance

Rest gathers many values into one array. Spread does the opposite: the same three dots, written before an array where values are expected, lay its items out one by one, as if each had been typed there by hand.

In a call, Math.max(...list) passes the items as separate numbers. In an array literal, [...a, ...b] joins two arrays into a new one, and [...a] alone makes a copy. The same dots gather in patterns and parameters, and spread wherever values are used. Which job they do depends on where they stand.

Take a guess: What happens when null is spread into an array, and into an object?

Rest gathers many values into one array. Spread does the opposite: the same three dots, written before an array where values are expected, lay its items out one by one, as if each had been written there by hand.

Spread syntax

Three dots before an array or other value that can be stepped through, ...list, in a call, an array literal or an object literal. The items are laid out in that place one by one.

Math.max wants separate numbers, not an array. Given an array, it tries to turn the array into one number, and fails:

const prices = [40, 15, 80];
console.log(Math.max(...prices), Math.max(prices));
80 NaN

Math.max(...prices) is the same call as Math.max(40, 15, 80). Spread can be mixed with ordinary arguments, in any place:

function f(a, b, c) {
  return a + b + c;
}
console.log(f(...[1, 2, 3]), f(1, ...[2, 3]));
6 6

Building new arrays

Inside square brackets, spread puts one array's items into a new array, anywhere among other items. A string can be spread too, into its characters:

const a = [1, 2];
const b = [3];
console.log([...a, ...b, 4], [..."chai"]);
[ 1, 2, 3, 4 ] [ 'c', 'h', 'a', 'i' ]

The shortest way to copy an array is to spread it into a new one. The copy is a different array, so pushing onto it leaves the original alone:

const a = [1, 2, 3];
const copy = [...a];
copy.push(4);
console.log(a, copy, a === copy);
[ 1, 2, 3 ] [ 1, 2, 3, 4 ] false

And to add an item without changing an array at all, build a new array with the old items and the new one. This matters in code that must never change data in place, which the React step will need:

const cart = [{ item: "tea", qty: 2 }];
const next = [...cart, { item: "dal", qty: 1 }];
console.log(cart.length, next.length);
1 2

Rest or spread? The place decides

Both are written as three dots, and the place tells them apart. Where names are being made, the dots gather; where values are being used, they spread.

Where the dots areWhat they doExample
in a pattern, on the left of =rest: gather what is leftconst [a, ...rest] = list;
in a function's parametersrest: gather the argumentsfunction f(...args)
in a call's argumentsspread: lay the items outf(...list)
inside [ ]spread: items into a new array[...a, ...b]
inside { }spread: properties into a new object{ ...obj }, in the next section

Worked example 5

A school has two sections of Class 9. Their marks are in two arrays. Find the highest mark of the whole class, and make one array of all the marks without changing either section's array.

What we have: two arrays of marks

What we need: one array of all marks, and the highest

The plan: spread both arrays into a new one, then spread that into Math.max

const sectionA = [72, 88, 91];
const sectionB = [95, 67];
const all = [...sectionA, ...sectionB];
console.log(all.length, Math.max(...all), sectionA.length);
5 95 3

The class has 5 marks, and the highest is 95.

Check: sectionA still has its 3 marks, so it was not changed.

A path that fails: sectionA.push(...sectionB). It gives the right marks, but it changes sectionA, and section A's own report then shows five students.

When you are stuck: spread gives NaN, an error, or a strange array

NaN from Math.max means an array went in without the dots.

An array inside an array means the dots were left out inside [ ].

TypeError: ... is not iterable means a plain object was spread inside [ ] or into a call; objects spread only inside { }.

Remember the copy is new: changes to it no longer reach the original.

Your turn

const n = [3, 9, 4];
console.log(Math.min(...n), [...n, ...n].length, [0, ...n][1]);
What does this print? Say your answer aloud first, then press Run or tap to reveal.Tap to reveal
3 6 3
  1. Math.min of 3, 9 and 4 is 3.
  2. Two copies of three items make six.
  3. [0, 3, 9, 4] has 3 at index 1.

It prints 3 6 3.

Make a new array that has every item of list, then the word end, without changing list.Tap to reveal
  1. Spread list into a new array, and write end after it.

const done = [...list, "end"];

How many items does [..."नमक"] have?Tap to reveal
console.log([..."नमक"].length);
3

It has 3 characters: न, म and क.

Did you know?

Nothing to spread

Spreading null behaves in two different ways. In an array or a call, ...null throws a TypeError: MDN's error page lists spreading into an array or a function call among the places where a value must be iterable. In an object literal, { ...null } is fine and adds nothing, because the standard's copying step stops at once when the source is undefined or null.

Why it fits here: It sharpens this topic's spread: in arrays and calls the value must be iterable, while object spread quietly skips null and undefined.

Sources: MDN: TypeError: 'x' is not iterable; ECMAScript Language Specification: CopyDataProperties

Before the dots: apply

Laying out an array as arguments was possible long before the three dots. The third edition of the standard, in 1999, already had Function.prototype.apply, which takes the arguments as an array: Math.max.apply(null, list). MDN still calls it common to use apply when the elements of an array should be a function's arguments, and shows spread syntax doing the same job more plainly.

Why it fits here: It explains a line often met in older code: apply did this topic's spread job, with an extra first argument for this.

Sources: ECMAScript Language Specification, 3rd edition (December 1999); MDN: Spread syntax

In one line

Spread lays an array's items out one by one: into a call (Math.max(...list)), or into a new array ([...a, ...b]), which also makes a copy. The same dots gather in patterns and parameters, and spread where values are used.

Copying and updating objects

At a glance

The Clock Tower's south face was given the north face's settings with one line, const south = north, and then its own chime. The north face's chime changed too, because = makes no copy at all.

Object spread makes a real copy: { ...obj, key: value } builds a new object with obj's properties and the changes written after, and the later property wins. It copies one level only, so inner arrays need new copies too. To change every value, use Object.entries with Object.fromEntries.

Take a guess: How do big state libraries update a deeply nested object without copying it all by hand?

The Clock Tower's south face was given the north face's settings with one line, const south = north;, and then its own chime. Here is what that does:

const north = { hour: 6, chime: "Bhairav" };
const south = north;
south.chime = "Yaman";
console.log(north.chime);
Yaman

As the objects lesson showed, = never copies an object. It gives a second name to the same object, so changing the south face's chime changed the only chime there is. A real copy needs a new object.

Object spread

Inside curly braces, three dots copy every property of an object into the new object being built. Properties written after the spread are added, or replace the copied ones:

const north = { hour: 6, chime: "Bhairav", volume: 8 };
const south = { ...north, chime: "Yaman" };
console.log(north.chime, south.chime, south.volume);
Bhairav Yaman 8

south is a new object with north's hour and volume, and a chime of its own. north is untouched. This pattern, a copy with a few changes, is the usual way to update data in modern code.

When two properties have the same name, the one written later wins. So the order decides which value is kept:

const o = { a: 1, b: 2 };
console.log({ ...o, a: 9 }, { a: 9, ...o });
{ a: 9, b: 2 } { a: 1, b: 2 }

In the second object, a: 9 came first and the spread came after it, bringing o's a of 1, which won. Write the changes after the spread. An undefined value still counts as written, so it replaces the copied one rather than leaving it:

const s = { theme: "dark", size: 2 };
const t = { ...s, size: undefined };
console.log(t);
{ theme: 'dark', size: undefined }

Still a shallow copy

Object spread copies one level, like Object.assign in the objects lesson. A property that holds an array or another object is copied as a reference, so the copy and the original share that inner value:

const o = { n: 1, list: [1] };
const copy = { ...o };
copy.list.push(2);
console.log(o.list);
[ 1, 2 ]

To change an inner array safely, give the copy a new array too, spread from the old one. Or, for data with many levels, use structuredClone:

const o = { n: 1, list: [1] };
const copy = { ...o, list: [...o.list, 2] };
console.log(o.list, copy.list);
[ 1 ] [ 1, 2 ]
WayCopiesWrites
{ ...o }the top levela new object, with changes after the spread
Object.assign({}, o)the top levelthe same, in an older style
structuredClone(o)every levela full copy that shares nothing, for plain data

Changing every value: entries and back

To change every value of an object, turn it into pairs with Object.entries, map the pairs, and turn them back into an object with Object.fromEntries. The map's arrow unpacks each pair with a pattern:

const prices = { tea: 15, dosa: 80 };
const raised = Object.fromEntries(Object.entries(prices).map(([item, p]) => [item, p + 5]));
console.log(raised);
{ tea: 20, dosa: 85 }

Worked example 6

The Clock Tower keeps each face's settings in an object, with a list of the hours at which it chimes. Make the south face's settings from the north's, with the chime Yaman and an extra chime at 21, without changing the north face in any way.

What we have: the north face's settings, with a chime and an hours array

What we need: new settings for the south face, and the north face unchanged

The plan: spread north into a new object, write the new chime after it, and give hours a new array spread from north's, with 21 added

const north = { chime: "Bhairav", hours: [6, 12, 18] };
const south = { ...north, chime: "Yaman", hours: [...north.hours, 21] };
console.log(north, south);
{ chime: 'Bhairav', hours: [ 6, 12, 18 ] } { chime: 'Yaman', hours: [ 6, 12, 18, 21 ] }

The south face chimes Yaman, at four hours; the north face still chimes Bhairav, at three.

Check: north printed exactly as it was made.

A path that fails: const south = { ...north, chime: "Yaman" }; followed by south.hours.push(21);. The chime is the south face's own, but hours is shared, so the north face starts chiming at 21 too.

When you are stuck: a copy changes the original

Check how the copy was made: = makes no copy at all.

Object spread copies one level: an inner array or object is still shared.

Give the copy new inner arrays or objects, spread from the old ones, or use structuredClone.

Write the changes after the spread; earlier ones are replaced by the copied values.

Your turn

const base = { size: "M", colour: "blue" };
const shirt = { colour: "red", ...base, size: "L" };
console.log(shirt.colour, shirt.size, base.size);
What does this print? Say your answer aloud first, then press Run or tap to reveal.Tap to reveal
blue L M
  1. colour: red is written first, then base's colour blue replaces it.
  2. size: L is written last, so it wins.
  3. base is unchanged: M.

It prints blue L M.

Make a copy of user with age set to 16, without changing user.Tap to reveal
  1. Spread user into a new object, and write age after it.

const older = { ...user, age: 16 };

Why does copy.tags.push("new") change the original after const copy = { ...post };?Tap to reveal
  1. Object spread copies one level.
  2. copy.tags and post.tags are the same array.

Because the copy is shallow: give the copy its own array with [...post.tags, "new"].

Did you know?

Spread changes nothing it copies

Spread and Object.assign look alike but behave differently. MDN notes that Object.assign can change the object it copies into, and triggers that object's setters, while spread syntax triggers no setters and changes no object: it always builds a new one. For this topic's copy-and-update, spread is the safer of the two.

Why it fits here: It explains why this topic copies with spread: the original object is never touched, and no hidden setter runs.

Sources: MDN: Spread syntax; ECMAScript 2018 Language Specification

Copying only what changed

Deep updates with spread grow long: every level on the way down must be copied by hand. Redux Toolkit wraps its update functions in a library called Immer, so a nested update can be written as one plain assignment. Its documentation says Immer copies exactly the levels that changed, as a careful chain of spreads would, and leaves the rest shared.

Why it fits here: It answers this topic's question: tools such as Immer do the level-by-level copying that this topic does by hand.

Source: Redux: Immutable Update Patterns

In one line

{ ...obj, key: value } makes a new object with obj's properties and the changes written after; the later property wins. It is a shallow copy, so give inner arrays new copies too, and use Object.entries with Object.fromEntries to change every value.

Where it is used

Destructuring and spread are in almost every modern file. Here is where each idea of this lesson does its work.

What you learnedWhere it is usedA real example
array patternsfunctions that return two answers; swappingconst [low, high] = lowHigh(marks);
object patternsreading data that arrives from a server or a fileconst { name, city } = customer;
patterns as parametersfunctions with many settings: options objectsbook({ from, to, seats })
patterns in for...ofreports made from an object's entriesfor (const [subject, mark] of Object.entries(marks))
restdropping a property; functions with any number of argumentsconst { token, ...safe } = settings;
spread in arrays and callsnew arrays that leave the old ones alone[...cart, newItem]
object spreadupdating data without changing it, as the React step will do{ ...north, chime: "Yaman" }

Mistakes and debugging

These are the slips that people meet most often with this lesson's ideas. Every output below is the real one, from the code shown.

1. Unpacking something that is not there

const items = [{ id: 1, name: "Tea" }];
const found = items.find((i) => i.id === 9);
const { name } = found;
Uncaught TypeError: Cannot destructure property 'name' of 'found' as it is undefined.
    at line 3

find gives undefined when nothing matches, and undefined cannot be unpacked. The fix: check first, if (found) { ... }, or unpack found ?? {}.

2. A plain object spread into an array

const shop = { name: "Ravi Stores" };
const list = [...shop];
Uncaught TypeError: shop is not iterable
    at line 2

The fix: spread objects only inside { }; for an array of its values, write Object.values(shop).

3. A rename read backwards

const shop = { name: "Ravi Stores" };
const { shopName: name } = shop;
console.log(name);
undefined

No error: the pattern looked for a property called shopName, which does not exist. The fix: the property comes first, { name: shopName }.

4. The change written before the spread

const north = { chime: "Bhairav", hour: 6 };
const south = { chime: "Yaman", ...north };
console.log(south.chime);
Bhairav

No error: the spread came later and brought north's chime back. The fix: { ...north, chime: "Yaman" }.

5. A shared inner array

const post = { title: "Notice", tags: ["school"] };
const copy = { ...post };
copy.tags.push("sports");
console.log(post.tags);
[ 'school', 'sports' ]

No error: the copy is shallow. The fix: { ...post, tags: [...post.tags, "sports"] }.

6. An array passed where values are wanted

const marks = [72, 95, 88];
console.log(Math.max(marks));
NaN

No error: Math.max tried to turn the whole array into one number. The fix: Math.max(...marks).

The debugging corner: print the shape

Most destructuring slips come from data that has a different shape from the pattern. Print the value just before the pattern with console.log(JSON.stringify(value)), then write the pattern beside it, name by name. For a copy that changes its original, compare the inner values with ===: copy.tags === post.tags is true when they are shared.

Quick card

The whole lesson on one card. Come back to it whenever you need a reminder.

The lesson in code

// arrays by position: skip a place, give a default
const [gold, , bronze = "none"] = ["Asha", "Ravi"];
console.log(gold, bronze);

// objects by name: rename, default, nested
const order = { id: 77, customer: { city: "Nagpur" } };
const { id: orderId, note = "none", customer: { city } } = order;
console.log(orderId, note, city);

// patterns in parameters (with = {}) and in loops over entries
const fare = ({ km = 0, rate = 15 } = {}) => km * rate;
for (const [item, price] of Object.entries({ tea: 15 })) {
  console.log(item, price, fare({ km: 2 }), fare());
}

// rest gathers, spread lays out
const [first, ...others] = [3, 9, 4];
console.log(first, others, Math.max(...others));

// a copy with changes: changes after the spread, inner arrays copied too
const north = { chime: "Bhairav", hours: [6, 18] };
const south = { ...north, chime: "Yaman", hours: [...north.hours, 21] };
console.log(north.hours.length, south.chime, south.hours.length);
Asha none
77 none Nagpur
tea 15 30 0
3 [ 9, 4 ] 9
2 Yaman 3
When you seeIt meansLook at
TypeError: Cannot destructure property ... of 'undefined'a pattern met undefined or null: a missing argument, or a search that found nothing= {} on the parameter, or a check first
TypeError: ... is not iterablea plain object spread inside [ ] or into a callspread objects only inside { }
SyntaxError: Rest element must be last elementsomething after the restmove the rest to the end
NaN from Math.maxan array passed without the dotsMath.max(...list)
a copy that changes its original= instead of a copy, or a shared inner arrayspread with new inner arrays, or structuredClone
an update that did not takethe change written before the spreadwrite changes after the spread

The story: Each face its own raga

You read the script. It never made a second set of settings at all: the south face was handed the north face's own, under a new name. You make the south face a new object instead, with every setting of the north face spread into it and its own raga written after them. Then you notice the list of hours is shared too, and give the south face a list of its own.

At dawn the north face chimes Bhairav again, and at dusk the south face answers with Yaman.

Master Verge writes a line in the tower's log. "Unpack what you need," he says, "and copy what you change. Most quarrels between programs start with one object and two owners."

Reagents gathered: destructuring, default value, rest parameter, spread syntax, object spread, Object.fromEntries.

Sources