Beginner · Arrays and objects · topic 19 of 61 · 25 min
Destructuring, spread and rest
Explanation
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
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 givenArray destructuring
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 1Nested destructuring and parameters
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 RaviSpread: 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.
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 16Rest: 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.
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 ... is | Name | What it does |
|---|---|---|
| In a function call or a literal [ ] { } | Spread | Spreads items or properties OUT |
| In a parameter list or on the left of = | Rest | Collects the remaining items IN |
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
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.
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)
Write fullAddress(person) that uses object destructuring to read city and pin and returns "<city> - <pin>".
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.
Write withoutSecrets(user) that returns a copy of user without the password and otp fields, using rest destructuring.
Quick quiz
Read more (free)
Related help
Before this, learn
This topic builds on these. If something here feels new, open them first.
Related topics
- References, copies and equalityArrays and objects · same module
- Array methods: map, filter, reduce and friendsArrays and objects · same module
- Objects in depthFrontend Web Development · JavaScript in depth
- More array powerFrontend Web Development · JavaScript in depth
- Compound types: tuples and arraysRust Programming · Types, control flow and functions
- Iterators and the iteration protocolMap, Set, iterators, generators and regular expressions
Questions people ask about this
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.
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
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 more topic in “Arrays and objects” before its exam: References, copies and equality.
- Module 4 exam: Arrays and objects · 12 questions · 25 min, without help. 5 topics of this module still to finish first.
- Then the next module, Scope, this, prototypes and classes. 61 topics left in the course before the final exam.