What is destructuring?

Destructuring is syntax for unpacking values from arrays (by position) or objects (by property name) into variables, with support for defaults, renaming, nesting and collecting the rest.

Object destructuring

  • Basic: const { name, age } = user.
  • Rename: const { name: fullName } = user.
  • Default: const { role = "viewer" } = user (applies only when the value is undefined).
  • Nested: const { address: { city } } = user.
  • Rest: const { password, ...safeUser } = user copies everything except password.

Array destructuring

  • By position: const [first, second] = list.
  • Skip items: const [, , third] = list.
  • Rest: const [head, ...tail] = list.
  • Swap without a temp variable: [a, b] = [b, a].

In function parameters

function render({ title, size = "md" }) {} documents the options a function takes and gives defaults in one place. Add = {} as a parameter default so calling with no argument does not throw.

Pitfalls

  • Destructuring null or undefined throws a TypeError. Provide a default (= {}) or use optional chaining before it.
  • Nested destructuring throws if an intermediate object is missing.
  • A statement starting with { is read as a block; wrap assignments in parentheses: ({ a, b } = obj).

Code example

js
1const user = {
2 name: "Ada",
3 role: undefined,
4 password: "secret",
5 address: { city: "London", zip: "N1" },
6};
7
8const { name: fullName, role = "viewer", address: { city } } = user;
9console.log(fullName, role, city); // Ada viewer London
10
11const { password, ...safeUser } = user; // drop a field
12console.log(safeUser); // { name, role, address } - no password
13
14const [first, , third = "none", ...others] = ["a", "b", undefined, "d", "e"];
15console.log(first, third, others); // a none ["d", "e"]
16
17let a = 1, b = 2;
18[a, b] = [b, a]; // swap
19console.log(a, b); // 2 1
20
21// Parameters with defaults; `= {}` makes the argument optional
22function createButton({ label = "OK", size = "md", disabled = false } = {}) {
23 return `${label} (${size}${disabled ? ", disabled" : ""})`;
24}
25console.log(createButton({ label: "Save", disabled: true })); // Save (md, disabled)
26console.log(createButton()); // OK (md)

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the JavaScript set.

Open in study app