JavaScript Tutorial · Objects and Arrays · Lesson 25 of 44

JavaScript Destructuring and Spread

Unpack arrays and objects into variables, and copy or merge with ...

Array destructuring

Pull values out of an array by position:

Example 1Try it yourself
const rgb = [255, 128, 0];
const [red, green, blue] = rgb;
console.log(red, green, blue);
const [first, ...rest] = [1, 2, 3, 4];
console.log(first, rest);
let a = 1, b = 2;
[a, b] = [b, a];  // swap
console.log(a, b);

Output

255 128 0
1 [ 2, 3, 4 ]
2 1

Object destructuring

Pull properties out of an object by name — with renaming and defaults:

Example 2Try it yourself
const user = { id: 7, name: "Ada", address: { city: "London" } };
const { name, role = "member", id: userId } = user;
console.log(name, role, userId);
const { address: { city } } = user;
console.log(city);

Output

Ada member 7
London

Spread: copy and merge

... inside an array or object literal copies items or properties. Later properties win, which makes spread perfect for "update" operations without mutating the original:

Example 3Try it yourself
const defaults = { theme: "light", lang: "en", fontSize: 14 };
const prefs = { theme: "dark" };
const settings = { ...defaults, ...prefs };
console.log(settings);
const nums = [1, 2];
const more = [0, ...nums, 3];
console.log(more, nums);
const original = { tags: ["a"] };
const copy = { ...original };
copy.tags.push("b");
console.log(original.tags);

Output

{ theme: 'dark', lang: 'en', fontSize: 14 }
[ 0, 1, 2, 3 ] [ 1, 2 ]
[ 'a', 'b' ]

Spread makes a shallow copy: nested objects are still shared. Use structuredClone(value) for a deep copy.

Test yourself

What does const { a = 5 } = { a: undefined } set a to?

  1. undefined
  2. 5
  3. null
  4. SyntaxError
Show answer

Answer: 5

Defaults apply when the value is undefined.