Skip to content
Destructuring and Spread/Rest
step 1/7

Reading — step 1 of 7

Learn

~3 min readModern Syntax

Destructuring (ES2015) and the spread/rest operator make modern JS dense — you'll see them in every codebase, every framework. Master them.

Array destructuring

Unpack array elements into variables:

javascript

Object destructuring

Unpack by property name:

javascript

Function parameter destructuring is huge for option objects:

javascript

No more options.name, options.age — destructure once at the top and the function body is clean.

Spread (...) — expand into pieces

For function arguments:

javascript

For array literals — concatenation, copying:

javascript

For object literals — merging:

javascript

This is the canonical "merge with defaults" pattern.

Rest (...) — collect into one

In function parameters — collect remaining args:

javascript

In destructuring — collect remaining elements/properties:

javascript

Rest must be LAST in the pattern. There's only one rest per pattern.

Common patterns

Immutable updates (React, Redux, etc.):

javascript

Removing a key (pull-out via destructuring rest):

javascript

Default options:

javascript

Common mistakes

  • Object destructuring in expression position{ a } = obj; is parsed as a block. Wrap: ({ a } = obj);.
  • Spread is shallow{...obj} only copies top-level. Nested objects are still shared. Use structuredClone(obj) or a deep-clone library.
  • Putting rest anywhere but last[...rest, last] is a syntax error; the rest element must come last.
  • Assuming spread merges arrays[...a, ...b] concatenates (a then b). It doesn't dedupe or sort.
  • Spreading a non-iterable in array context[...obj] for a plain object throws. Use Object.entries(obj) or Object.values(obj) first.

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…