Destructuring, Every Corner
Defaults, renaming, nesting, swapping and destructuring in function parameters.
Syntax
const { a, b: c = 1, ...rest } = obj;
const [x, , z] = arr;Destructuring is pattern matching for assignment. The pattern on the left mirrors the shape of the data on the right.
All the moves at once
const {
id,
name: fullName = 'Anon', // rename + default
address: { city } = {}, // nested, with guard default
...others // rest of the props
} = user;Array patterns
Skip with holes, gather with rest, and swap without a temp: [a, b] = [b, a].
Parameter destructuring
The killer use: unpack an options object right in the signature, with defaults, so callers pass named arguments in any order.
function draw({ x = 0, y = 0, color = 'black' } = {}) {}That trailing = {} lets draw() work with no argument at all.
Example
Loading editor…
Press Run to execute the code.
When to use it
- Swap two state variables atomically using array destructuring in a React reducer.
- Destructure a nested API response to extract only city and country from a user's address.
- Use destructuring in function parameters to document which fields a handler depends on.
More examples
Nested object destructuring
Destructures two levels deep in one statement to extract id and city from a nested API response.
const resp = { user: { id: 1, address: { city: "Oslo", zip: "0150" } } };
const { user: { id, address: { city } } } = resp;
console.log(id, city); // 1 "Oslo"Destructure with rename and default
Renames theme to colorScheme and supplies a default for the absent lang property.
const settings = { theme: "dark" };
const { theme: colorScheme = "light", lang = "en" } = settings;
console.log(colorScheme, lang); // "dark" "en"Mixed array and object destructuring
Combines array and object destructuring in one expression to extract a name and first score.
const data = [{ name: "Alice", scores: [95, 87] }, { name: "Bob", scores: [72, 80] }];
const [{ name, scores: [top] }] = data;
console.log(name, top); // "Alice" 95
Discussion