Destructuring & spread
Unpack arrays and objects, set defaults, rename, and copy or merge with ... spread and rest.
Destructuring unpacks values from arrays and objects into variables. Spread (...) expands them into new arrays, objects or function arguments, and rest (also ...) gathers the leftovers. Together they make modern JavaScript concise — and they're everywhere in React code.
Array destructuring#
Values are assigned by position:
Swapping variables
Rest in arrays
The rest element must be last.
Functions returning multiple values
This is exactly how React's const [count, setCount] = useState(0) works.
Object destructuring#
Values are assigned by property name, so order doesn't matter:
Renaming and defaults
Read theme: currentTheme as "take theme and call it currentTheme". Defaults apply only when the value is undefined, not null.
Rest in objects
A neat way to remove a property without mutating the original.
Nested destructuring
Nested destructuring throws if an intermediate value is missing (customer undefined). For uncertain data, provide defaults (customer: { name } = {}) or use optional chaining.
Destructuring in function parameters#
This is where destructuring shines — named, self-documenting options:
Add = {} so the function can be called with no argument at all:
Destructuring works in loops and callbacks too:
Spread with arrays#
Spread with objects#
Order matters: later properties overwrite earlier ones. Put defaults first and overrides last.
Immutable updates of nested data
Every level you change gets a new copy; everything else is shared. This is the core pattern for updating React state.
Rest vs spread: same dots, opposite jobs#
Rule of thumb: on the left of = or in a parameter list it gathers (rest); on the right or in a call it expands (spread).
Common mistakes#
- Destructuring
nullorundefined:const { a } = nullthrows a TypeError. Use= {}defaults. - Forgetting parentheses when destructuring into existing variables:
({ a, b } = obj);— without them,{starts a block. - Expecting spread to deep-copy nested objects.
- Spreading huge arrays into function arguments (
Math.max(...hugeArray)) can exceed the engine's argument limit — usereducefor very large arrays.
What's next#
You can now work fluently with data. Next, take it to the browser: select, create and change elements with the DOM.
Check your understanding
Quick quiz
1.What is
bafterconst [a, , b] = [1, 2, 3];?2.What does
const { title: heading = "Untitled" } = {};create?3.What is
{ ...{ a: 1, b: 2 }, b: 3 }?
Finished reading?
Mark this lesson complete to track your progress.