Data & LogicIntermediate7 min08 / 23

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

arrays by position, objects by name
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); // London

Objects destructure by property name (order doesn't matter); arrays destructure by position. It's especially handy for function parameters.

spread: copy & combine
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]
Note

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.

Quick check

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.
Practice challenges
Test yourself · earn XP
0/3
Predict the output#1

What does this print?

predict-output
const { a, b = 2 } = { a: 1 };
console.log(a, b);
Predict the output#2

What is `combined`?

predict-output
const x = [1, 2];
const y = [3, 4];
const combined = [...x, ...y];
console.log(combined);
Fill in the blank#3

Complete the copy-with-override to set `read` to true without mutating `msg`.

const seen = { msg, read: true };
Your turn
Practice exercise

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:

solution.js · editable