Destructuring & Spread
Unpack values out of arrays and objects, and spread them back in — the modern syntax you'll see in every codebase.
Destructuring pulls values out of arrays and objects into variables in one line. Spread (...) does the opposite — it expands an array or object into another one. Together they make working with data far cleaner.
#Destructuring
const [first, second] = ['a', 'b', 'c'];
console.log(first, second); // a b
const user = { name: 'Ada', age: 36, city: 'London' };
const { name, age } = user;
console.log(name, age); // Ada 36
// with defaults + renaming
const { city: hometown = 'Unknown' } = user;
console.log(hometown); // LondonObjects destructure by property name (order doesn't matter); arrays destructure by position. It's especially handy for function parameters.
const a = [1, 2];
const b = [3, 4];
const all = [...a, ...b]; // [1, 2, 3, 4]
const base = { theme: 'dark' };
const settings = { ...base, fontSize: 14 }; // { theme: 'dark', fontSize: 14 }
// rest: collect the remainder
const [head, ...tail] = [10, 20, 30];
console.log(head, tail); // 10 [20, 30]Spread makes a shallow copy
{ ...obj } and [...arr] create a new top-level array/object — great for updating state immutably. But nested objects are still shared references, so it's a shallow copy.
What is `rest` after `const [x, ...rest] = [1, 2, 3, 4];`?
Key takeaways
- Array destructuring is by position; object destructuring is by property name.
- You can set defaults and rename while destructuring: `{ city: hometown = 'Unknown' }`.
- Spread `...` expands arrays/objects to copy or combine them.
- The rest pattern `...rest` collects leftover elements/properties.
- Spread copies are shallow — nested values are shared.
What does this print?
const { a, b = 2 } = { a: 1 };
console.log(a, b);What is `combined`?
const x = [1, 2];
const y = [3, 4];
const combined = [...x, ...y];
console.log(combined);Complete the copy-with-override to set `read` to true without mutating `msg`.
const seen = { msg, read: true };
Use destructuring and spread to (1) pull title out of post, and (2) create updated, a copy of post with views set to 0.
``js const post = { title: 'Hi', author: 'Ada', views: 42 }; ``
Try it live — edit the code and hit Run to see the output: