Skip to content

Beginner · Arrays and objects · topic 19 of 61 · 25 min

Destructuring, spread and rest

Explanation

Destructuring unpacks values from arrays and objects into variables in one line: const { name, city } = user. Spread (...) copies the items of an array or the properties of an object into a new one, which is how modern code copies and merges data. Rest (...) collects "everything else" while destructuring.

Why destructuring?

Code often needs several properties of one object: const name = user.name; const city = user.city; const age = user.age;. Destructuring does this in one line and makes it obvious which fields you use.

Object destructuring

javascript
const user = { name: 'Meena', city: 'Kochi', age: 29 };
const { name, city } = user;
console.log(name, city);              // Meena Kochi

const { age: years, phone = 'not given' } = user;  // rename and default
console.log(years, phone);            // 29 not given
Names are matched by KEY, so order does not matter.

Array destructuring

javascript
const [first, second, ...others] = ['gold', 'silver', 'bronze', 'fourth'];
console.log(first, second, others); // gold silver ['bronze', 'fourth']

const [, , third] = ['a', 'b', 'c'];  // skip with commas
console.log(third);                   // 'c'

let a = 1, b = 2;
[a, b] = [b, a];                      // swap without a temporary variable
console.log(a, b);                    // 2 1
Array destructuring matches by POSITION.

Nested destructuring and parameters

javascript
const order = { id: 7, customer: { name: 'Ravi', address: { pin: '600001' } } };
const { customer: { name: buyer, address: { pin } } } = order;
console.log(buyer, pin); // Ravi 600001

function label({ id, customer: { name } }) {
  return `#${id} for ${name}`;
}
console.log(label(order)); // #7 for Ravi
Careful: Destructuring a property of undefined or null throws: const { name } = undefined gives TypeError: Cannot destructure property. When the whole object may be missing, give a default: const { name } = maybeUser ?? {}; or in a parameter, function f({ name } = {}).

Spread: copy and merge

Spread (...) in an array literal or object literal copies the items or properties of another array or object into the new one. This is the everyday way to copy and merge without changing the originals.

javascript
const veg = ['paneer', 'dal'];
const nonVeg = ['chicken'];
const menu = [...veg, ...nonVeg, 'roti'];     // ['paneer', 'dal', 'chicken', 'roti']

const defaults = { theme: 'light', lang: 'en', fontSize: 14 };
const saved = { lang: 'hi' };
const settings = { ...defaults, ...saved };  // later keys win
console.log(settings); // { theme: 'light', lang: 'hi', fontSize: 14 }

const updated = { ...settings, fontSize: 16 }; // copy with one change
console.log(settings.fontSize, updated.fontSize); // 14 16

Rest: everything else

Three dots on the LEFT side of a destructuring collect the remaining items or properties. This is handy to remove a field without changing the original.

javascript
const account = { id: 5, name: 'Asha', password: 'secret123' };
const { password, ...safeAccount } = account;
console.log(safeAccount); // { id: 5, name: 'Asha' } (safe to send to the browser)
Where the ... isNameWhat it does
In a function call or a literal [ ] { }SpreadSpreads items or properties OUT
In a parameter list or on the left of =RestCollects the remaining items IN
Think of it like this: Spread is like emptying several shopping bags onto one table: everything ends up together, and when two bags have the same item, the one emptied last sits on top. Rest is like keeping one item in your hand and putting "everything else" back into a bag.
Tip: Spread makes a SHALLOW copy: nested objects inside are still shared. The next topic shows what that means and how to make a deep copy.

Need help?

Stuck on a word or an idea? Search this course, or every course, and jump straight to the explanation or a worked question.

Try:

Watch the lesson

Destructuring, spread and rest · 1/6

Destructuring · spread · rest

In this lesson you will unpack and copy data with destructuring, spread and rest.

Prefer a video by a teacher? Find free videos on “javascript destructuring spread rest operator tutorial” on YouTube ↗

In real life: Updating a user profile in a React-style app

Front-end frameworks like React want state to be replaced, not changed in place. When the user edits their city, the app makes a new profile object with spread, changing only one field, and removes the password with rest before logging it.

javascript
const profile = { name: 'Kabir', city: 'Indore', password: 'p@ss' };
const next = { ...profile, city: 'Bhopal' };
const { password, ...loggable } = next;
console.log(loggable); // { name: 'Kabir', city: 'Bhopal' }

Practice (0/3 done)

Task 1 · Code · Javascript

Write fullAddress(person) that uses object destructuring to read city and pin and returns "<city> - <pin>".

Task 2 · Code · Javascript

Write mergeSettings(defaults, userSettings) that returns a new object with the defaults overridden by the user settings. userSettings may be undefined. Neither input may change.

Task 3 · Code · Javascript

Write withoutSecrets(user) that returns a copy of user without the password and otp fields, using rest destructuring.

Quick quiz

Question 1

1.const [x, , y] = [1, 2, 3]; What are x and y?

Question 2

2.const { a = 5 } = { a: null }; What is a?

Question 3

3.What is { ...{ x: 1, y: 2 }, ...{ y: 9 } }?

Question 4

4.In function f(...args), the three dots are called…

Read more (free)

Open a question to see the answer and why. The first ones are this topic's own quiz, so try the quiz above before you peek.

const [x, , y] = [1, 2, 3]; What are x and y?

Answer: 1 and 3

The empty slot skips the second item.

const { a = 5 } = { a: null }; What is a?

Answer: null

Defaults apply only to undefined; null is kept.

What is { ...{ x: 1, y: 2 }, ...{ y: 9 } }?

Answer: { x: 1, y: 9 }

Later properties overwrite earlier ones with the same key.

In function f(...args), the three dots are called…

Answer: rest

In a parameter list they collect arguments: rest.

Where must a rest parameter go?Related

Answer: Last

Rest collects everything that is left, so it must be the last parameter.

From Parameters: defaults, rest and options objects

const key = 'city'; Which line reads the city of user?Related

Answer: user[key]

Brackets use the value of the variable, so user[key] is the same as user.city. user.key looks for a key literally named "key".

From Objects in depth

const [a, ...rest] = [1, 2, 3]; What is rest?Related

Answer: [2, 3]

a takes the first item, and ...rest collects everything that is left into a new array.

From More array power

Which is a valid array type for five f64 values?Related

Answer: [f64; 5]

Array types are written [type; length].

From Compound types: tuples and arrays

Pass the quiz (60% or more) or mark this topic as done when you are ready.

Your progress is saved on this device only.

Next steps

  1. 1 more topic in “Arrays and objects” before its exam: References, copies and equality.
  2. Module 4 exam: Arrays and objects · 12 questions · 25 min, without help. 5 topics of this module still to finish first.
  3. Then the next module, Scope, this, prototypes and classes. 61 topics left in the course before the final exam.

← Previous: Objects: keys and values