Destructuring and Spread
Pulling values out of arrays and objects with destructuring — nested, renamed, defaulted — and building new ones with the spread operator.
Arrays and Array MethodsDefault, Rest, and Spread Parameters
Destructuring and Spread
The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.
Not started
What you'll learn
- Destructuring is pattern-matching for pulling values out of an array or object into standalone variables in one step — `const [first, second] = arr` and `const { name, age } = user` both skip the usual `arr[0]`/`user.name` indexing.
- Destructuring patterns can rename on the way out, default a value when the source is `undefined`, and nest arbitrarily deep to reach into an object or array buried inside another one — all in a single declaration.
- The spread operator (`...`) inside an array or object literal does the opposite job of destructuring: it expands an existing array or object's elements/properties into a new literal, which is how you copy or merge data without mutating the source.
- Both array and object spread only copy one level deep — a nested object or array inside the thing you spread is still the *same* nested reference in the copy, not a new one, which is a common source of \"I copied it but it still mutated the original\" bugs.
- Object spread's last-one-wins rule (`{ ...defaults, ...overrides }`) is the idiomatic way to layer a set of overrides on top of defaults, and it reads left to right exactly like you'd expect: later keys win.
Pulling values out without the indexing boilerplate
Once you’re comfortable with arrays and objects, a specific kind of code
shows up constantly: you have a container, and you just want a few values
out of it, into their own named variables, right now. The obvious way is
indexing — const first = arr[0], const name = user.name — and it works
fine for one value. It gets noisy fast once you need five fields out of a
response object, or you’re unpacking a tuple-like array where position
means something specific.
Destructuring is JavaScript’s answer: a pattern on the left-hand side of an assignment that mirrors the shape of the data on the right, and pulls matching pieces straight into variables.
const [first, second] = [10, 20]; // first = 10, second = 20
const { name, age } = { name: "Ada", age: 31, active: true }; // name = "Ada", age = 31
The array version matches by position; the object version matches by key name, ignoring whatever else is on the object. Both skip the index/property lookup entirely — you declare what you want, and the shape of the pattern does the rest.
Patterns that rename, default, and nest
Plain destructuring is already useful, but three extensions make it cover nearly every real-world shape you’ll run into.
Renaming lets the variable name differ from the source key — handy when the source name is generic or would collide with something already in scope:
const { name: userName } = user; // pulls `name`, but the variable is `userName`
Defaults fill in a value when the source is undefined, which matters
most for optional fields and function parameters:
const { retries = 3 } = options; // retries is 3 if options.retries is undefined
Nesting lets the pattern mirror data buried several levels deep, so you never have to introduce a throwaway variable just to drill down one step:
const { address: { city } } = user; // reaches straight through `address` to `city`
All three compose — you can rename and default and nest in the same pattern. The embedded video builds up exactly this progression, starting from basic array and object destructuring and layering in the same kind of practical cases — pulling apart function arguments, picking fields out of a fetched object — that make the syntax click once you’ve seen it solve an actual annoyance rather than a toy example.
Spread: building new things instead of pulling values out
Spread syntax (...) inside an array or object literal does roughly the
opposite job of destructuring. Instead of pulling pieces out of an
existing structure, it expands an existing structure’s elements or
properties into a new literal you’re building:
const nums = [1, 2, 3];
const withFour = [...nums, 4]; // [1, 2, 3, 4] — a new array, nums untouched
const user = { name: "Ada", age: 31 };
const updated = { ...user, age: 32 }; // { name: "Ada", age: 32 } — a new object
This is the standard way to copy or merge arrays and objects without mutating the originals — which matters constantly in UI code and anywhere else you’re expected to treat data as immutable. Object spread also gives you a clean way to layer overrides on top of defaults, since later spreads win over earlier ones for any key they share:
const config = { ...defaults, ...userOverrides }; // userOverrides wins ties
This lesson is specifically about spread inside array and object
literals — building a new array or object. There’s a second, related use
of the same ... syntax at a function call site (fn(...args)) and in
function parameter lists (function fn(...rest)), which is its own
lesson; the two share a symbol but solve different problems, so this
lesson won’t re-tread that ground.
The one-level-deep trap
Both array and object spread copy only their top level. If a property you spread is itself an object or array, the copy’s property still points at the exact same nested value the original does:
const original = { address: { city: "Accra" } };
const copy = { ...original };
copy.address.city = "Lagos";
console.log(original.address.city); // "Lagos" — the "copy" wasn't independent
copy got its own address key, but the value of that key — the nested
object — was never duplicated, just referenced twice. This is the single
most common surprise with spread, and it’s worth internalizing now: spread
gives you a shallow copy, full stop. A true deep copy means spreading (or
otherwise cloning) every nested level yourself.
Where this fits
This lesson assumes you’re already comfortable with array methods — a lot
of destructuring targets are the arrays those methods produce — and with
function parameter spread/rest, which this lesson deliberately doesn’t
repeat. From here, destructuring and spread become the default vocabulary
for working with the next two topics in this group: Map/Set entries
destructure the same way array entries do, and the iterator protocol
underneath for...of is exactly what makes array destructuring and spread
possible on anything iterable, not just arrays.
Check yourself
What does `const { name, age = 0 } = user` do if `user` has no `age` property at all?
`age` gets the default value `0`. A destructuring default only kicks in when the corresponding property is `undefined` (including genuinely missing), so a missing `age` property falls through to the default exactly as if `user.age` were explicitly set to `undefined`.
How would you destructure `const response = { data: { user: { id: 1 } } }` to get `id` directly into a variable, in one statement?
`const { data: { user: { id } } } = response;` — nested destructuring mirrors the shape of the data, drilling down through `data` and `user` without creating intermediate variables for either.
You write `const copy = { ...original }; copy.address.city = "Lagos";` and now `original.address.city` has also changed. Why, even though you "copied" the object?
Object spread only copies one level deep. `copy` got its own top-level properties, but `copy.address` is still a reference to the exact same nested object `original.address` points to — so mutating a property *inside* that nested object affects both. A real deep copy needs to spread (or clone) each nested level separately.
What's the difference between `const [a, b] = [1, 2, 3]` and `const { 0: a, 1: b } = [1, 2, 3]`?
Functionally almost nothing — array destructuring is really just object destructuring by numeric-key, since arrays are objects with numeric keys. The square-bracket form is purely the idiomatic, readable shorthand for exactly that pattern.
Given `const settings = { ...defaults, ...userPreferences }`, which object's values win if both `defaults` and `userPreferences` define the same key?
`userPreferences`, because object spread applies left to right and a later spread's properties overwrite an earlier spread's properties for any key they share — same rule as assigning object literal keys in order.
Go deeper
Notes
Notes are saved to your account.
Everything else on this page works without one — progress and bookmarks keep themselves in this browser and come with you when you sign in. Notes are the one thing worth not trusting to a browser you might clear.
Your notes could not be loaded.