Destructuring, Spread, and Rest
Three related bits of syntax built on ... and pattern-matching — pulling values out, copying/combining data, and gathering leftovers.
const { a, b } = obj; / const [x, y] = arr; / [...arr, x] / { ...obj, key }
Purpose
Destructuring extracts values from an array or object into individual bindings. Spread (...)
expands an array or object’s contents into a new array, object, or argument list — the standard way
to copy or combine data. Rest (also ..., in the opposite position) gathers remaining values
instead of spreading them out.
Syntax
// Destructuring
const { x, y } = { x: 10, y: 20, z: 30 }; // pulls out x and y only
const [first, second] = [1, 2, 3]; // pulls out the first two elements
// Spread — copy/combine
const copy = [...[1, 2, 3], 4]; // [1, 2, 3, 4]
const merged = { ...{ theme: 'dark' }, fontSize: 16 }; // { theme: "dark", fontSize: 16 }
// Rest — gather leftovers
function sum(first, ...rest) {
return rest.reduce((total, n) => total + n, first);
}
const [head, ...tail] = [1, 2, 3, 4]; // head = 1, tail = [2, 3, 4]
Behavior notes
- Destructuring can rename (
const { x: xPos } = point;) and supply defaults (const { retries = 3 } = config;) in the same step. - Spread copies are shallow: nested objects/arrays inside the spread structure are still shared by reference between the original and the copy.
- Spreading a later property over an earlier one in an object literal overwrites it — property
order in
{ ...a, ...b }matters, withb’s properties winning on conflict. - Rest must be the last item in a destructuring pattern or parameter list —
function f(...rest, last)is aSyntaxError.
Common mistakes
- Assuming
{ ...obj }deep-copies — mutating a nested object reached through the copy still affects the original. See Arrays and Objects for the full explanation. - Destructuring a property that doesn’t exist without a default — the resulting binding is simply
undefined, not an error, which can silently propagate rather than failing loudly.
Runtime notes
Destructuring and spread/rest are ECMAScript language features (ES2015 and later) with identical behavior across browsers and Node.