Intermediate · 10 of 17 · 15 min read
Destructuring
Pulling values out of arrays and objects by shape, with defaults, renaming and nesting — and the three syntax traps.
- Destructuring
Destructuring binds variables by matching the shape of a value. Arrays match by position, objects match by key. It is the most-used ES2015 feature and the one with the most small traps.
Arrays, by position
const [first, second] = [1, 2, 3];
console.log(first, second); // 1 2
const [, , third] = [1, 2, 3]; // holes skip positions
console.log(third); // 3
const [head, ...tail] = [1, 2, 3]; // rest collects the remainder
console.log(head, tail); // 1 [2, 3]
const [a = 10, b = 20] = [1]; // defaults for missing positions
console.log(a, b); // 1 20
let x = 1, y = 2;
[x, y] = [y, x]; // swap, no temporary
console.log(x, y); // 2 1
It works on anything iterable, not just arrays:
const [c1, c2] = 'hi';
console.log(c1, c2); // "h" "i"
const [k, v] = ['a', 1];
console.log(k, v); // "a" 1
for (const [key, value] of Object.entries({ a: 1 })) console.log(key, value); // a 1
const [firstOfSet] = new Set([5, 6]);
console.log(firstOfSet); // 5
Objects, by name
const user = { name: 'Ana', age: 30, city: 'Rosario' };
const { name, age } = user;
console.log(name, age); // "Ana" 30
const { name: fullName } = user; // rename
console.log(fullName); // "Ana"
const { country = 'AR' } = user; // default for a missing key
console.log(country); // "AR"
const { city: where = 'unknown' } = user; // rename *and* default
console.log(where); // "Rosario"
const { name: n, ...rest } = user; // rest gathers the others
console.log(rest); // { age: 30, city: 'Rosario' }
Order does not matter and extra properties are ignored, which is what makes object destructuring safe against API changes that only add fields.
A computed key, for when the name is in a variable:
const key = 'age';
const { [key]: value } = user;
console.log(value); // 30
Defaults fire only for undefined
The single most common destructuring bug:
const { a = 'default' } = { a: undefined };
console.log(a); // "default"
const { b = 'default' } = { b: null };
console.log(b); // null — `null` is a value, so the default does not apply
const { c = 'default' } = { c: 0 };
console.log(c); // 0
const { d = 'default' } = {};
console.log(d); // "default" — missing is undefined
| Source value | Default applies |
|---|---|
| missing key | yes |
undefined |
yes |
null |
no |
0, '', false, NaN |
no |
So a JSON API that sends null for “no value” defeats your defaults. Handle it explicitly:
const response = { nickname: null };
const { nickname } = response;
console.log(nickname ?? 'anonymous'); // "anonymous"
A default can be any expression, and it is evaluated lazily — only when it is needed:
function expensive() {
console.log('computed');
return 99;
}
const { present = expensive() } = { present: 1 };
console.log(present); // 1 — "computed" was never logged
const { missing = expensive() } = {};
console.log(missing); // "computed" then 99
Later bindings can reference earlier ones:
const { width = 10, height = width * 2 } = { width: 5 };
console.log(width, height); // 5 10
Nesting
const data = {
user: { name: 'Ana', address: { city: 'Rosario' } },
tags: ['js', 'node'],
};
const {
user: {
name,
address: { city },
},
tags: [firstTag],
} = data;
console.log(name, city, firstTag); // "Ana" "Rosario" "js"
Note what nesting does not do: user: and address: are patterns, not bindings. Those names
do not exist afterwards.
// console.log(user); // ReferenceError — only `name`, `city` and `firstTag` were bound
And a missing intermediate level throws, because you cannot destructure undefined:
const partial = {};
// const { user: { name } } = partial; // TypeError: Cannot destructure property 'name'
const { user: { name: safeName } = {} } = partial; // a default at each level
console.log(safeName); // undefined
For anything deeper than two levels, optional chaining is usually clearer than nested defaults:
console.log(partial.user?.address?.city ?? 'unknown'); // "unknown"
In parameters
This is where it earns its keep daily: named arguments with defaults, and a signature that states the contract.
function createUser({ name, role = 'member', active = true } = {}) {
return `${name} · ${role} · ${active}`;
}
console.log(createUser({ name: 'Ana' })); // "Ana · member · true"
console.log(createUser({ role: 'admin', name: 'Beto' })); // order does not matter
console.log(createUser()); // "undefined · member · true"
The = {} is required if the function must be callable with no arguments:
function strict({ a }) { return a; }
// strict(); // TypeError: Cannot destructure property 'a' of undefined
| Positional parameters | Destructured object | |
|---|---|---|
| Call site readability | f(1, true, null, 3) |
f({ retries: 3 }) |
| Order matters | yes | no |
| Skipping an optional one | pass undefined |
omit the key |
| Adding a parameter later | changes every call | additive |
| Visible in the signature | yes | yes — that is the point |
Array destructuring in parameters is how map callbacks read entries:
const entries = [['a', 1], ['b', 2]];
console.log(entries.map(([key, value]) => `${key}=${value}`)); // ["a=1", "b=2"]
Where it already appears
import { useState } from 'react'; // not destructuring, but the same shape
const [state, setState] = [0, () => {}]; // the hook's return, destructured
const { data, error } = await getResult(); // the common async idiom
const { pathname } = new URL('https://x.dev/a/b');
console.log(pathname); // "/a/b"
try {
null.x;
} catch ({ name, message }) { // catch binding destructures too
console.log(name); // "TypeError"
}
Common mistakes
Assigning without a declaration and no parentheses
Mistake. { a, b } = obj; on its own line.
Why it fails. A statement that starts with { is parsed as a block, not an object pattern,
so it is a SyntaxError.
What to do instead. Wrap it: ({ a, b } = obj);
let a, b;
// { a, b } = { a: 1, b: 2 }; // SyntaxError
({ a, b } = { a: 1, b: 2 }); // fine
console.log(a, b); // 1 2
The missing semicolon before an array pattern
Mistake. A line ending without ; followed by [x, y] = [y, x].
Why it fails. The [ is read as an index on the previous line’s value, so the two statements
merge into one nonsensical expression.
What to do instead. Terminate statements, or start the line with a semicolon: ;[x, y] = ….
Expecting a default to cover null
Mistake. const { avatar = '/default.png' } = user where the API sends null.
Why it fails. Only undefined triggers a default, so avatar is null and the image breaks.
What to do instead. const avatar = user.avatar ?? '/default.png', or normalise null to
undefined at the boundary.
Check yourself
3 questions from the bank on what you just read. Answering here does not affect your quiz history.
A destructuring default has a precise trigger condition.
What does this log?
const { a = 1 } = { a: null };
console.log(a);Destructuring can rename as it extracts, and the syntax reads backwards from what people expect.
What does this log?
const user = { name: "Ana", age: 30 };
const { name: label, city = "N/A" } = user;
console.log(label, city);What does declaring a function as function f({ a, b }) buy you over function f(options)?
Further reading
Everything above is meant to be enough on its own. These are for when you want the full specification of a detail.
Reaching the end of a lecture marks it as read.