JavaScript Destructuring, Spread and Rest Syntax
Destructuring pulls values out of arrays and objects into separate variables in one statement. Spread does the opposite: it expands an array or object into individual items. Together they replace a lot of repetitive code, and you will see both in nearly every modern code base.
Array destructuring
const [first, second, ...rest] = [10, 20, 30, 40]; assigns by position. The ...rest element collects whatever is left into a new array. You can skip positions with an empty slot, as in const [, second] = arr;. Destructuring also gives the neatest swap in the language: [a, b] = [b, a];.
Object destructuring
const { title, year: published, stock = 0 } = book; assigns by property name:
titlecreates a variable with the same name as the property.year: publishedreadsyearbut stores it in a variable calledpublished.stock = 0supplies a default when the property is missing orundefined.
Function parameters can be destructured too. function describe({ title, year }) pulls the two properties straight out of whatever object is passed, so callers can pass one options object instead of a long list of arguments.
Expected output
10 20 [30, 40]
Desert Gardens 2012 0
2 1
{title: "Desert Gardens", year: 2012, price: 19.99} 22
[30, 40, 50, 60] 60
Desert Gardens (2012)Spread
Three dots in an array literal or function call expand an iterable: [...rest, ...[50, 60]] concatenates, and Math.max(...merged) passes every number as a separate argument.
In an object literal, { ...book, price: 19.99 } copies all of book's properties into a new object, then overrides price. Later properties win, so put overrides after the spread. The original book keeps its price, as the output shows.
These copies are shallow: nested objects and arrays are still shared between the copy and the original. For a full deep copy of plain data, structuredClone(obj) is available in current browsers and Node.js.
Rest versus spread
The same three dots mean "collect" on the left side of an assignment or in a parameter list (rest), and "expand" in an expression (spread).
Common mistakes
- Destructuring a property from
undefined, which throws. Give parameters a default:function f({ a } = {}). - Expecting spread to deep-copy nested data.
- Starting a line with
[after a line without a semicolon. Write the semicolon, as the example does before the swap.
Summary
[a, b] = arrunpacks by position;{ a, b } = objunpacks by name.- Rename with
key: newName; add defaults with= value. ...collects (rest) or expands (spread); object spread makes shallow copies.
Quiz: Destructuring and spread