Step 1 of 7 · Reading · ~4 min
Learn
Modern Syntax
Destructuring and Spread/Rest
Destructuring unpacks an array or object into separate variables in one statement. Spread and rest, both written ..., expand a collection into pieces or gather pieces into a collection. By the end of this lesson you can read and write all of them.
Array destructuring: by position
The pattern on the left mirrors the shape on the right, and each name takes the item in the same position. You can skip positions with an empty slot and supply defaults that apply when the position is undefined (missing):
A default only fills in for undefined. An empty string or null in that position is a real value and is kept.
Destructuring also swaps two variables with no temporary:
Object destructuring: by name
The same patterns work in a function's parameter list, which is the usual way to accept an "options" object with defaults:
Destructuring a name that is not at the start of a statement needs parentheses: ({ title } = book);, since a line starting with { is read as a block.
Rest: gather the remainder
...name in a pattern collects everything not already named. It must come last, and only once.
If nothing is left over, the rest variable is an empty array (or object). In function parameters, ...args does the same job for arguments:
Spread: expand into pieces
Spread is the mirror image: in a call or a literal, ...x unpacks the items of x in place.
In an object, later keys overwrite earlier ones, so putting your overrides after ...defaults is the "merge with defaults" pattern. { ...state, count: 5 } is also how you make an updated copy without touching the original. Two things to remember: spread copies one level deep (nested objects stay shared), and [...obj] on a plain object throws because objects are not iterable.
To drop a key from a copy, pull it out with rest: const { secret, ...safe } = user;.
Common mistakes
- Using the wrong names in object destructuring.
{ titel } = bookquietly givesundefined. - Expecting a default to replace
nullor"". Onlyundefinedtriggers it. - Putting the rest element anywhere but last, which is a syntax error.
- Mixing up spread and rest:
...in a pattern or parameter list collects,...in a call or literal expands. - Assuming the copy made by spread is deep.
Your exercise
Parse a comma-separated record into named variables in a single destructuring statement, with defaults for fields that may be absent and a rest for the leftovers. The starter splits the line into fields.
Discussion
Ask a question, share an insight, or help someone who’s stuck.
Sign in to post a comment or reply.
Loading…