Lesson 8 of 50JavaScript basics
Destructuring, Spread and Safe Access
Unpack values with destructuring, copy and merge with spread, and read nested data safely with ?. and ??.
Open any modern React or Node file and you will see const { data, error } = ..., { ...state, loading: true } and user?.address?.city ?? "Unknown" within the first twenty lines. These few symbols carry a lot of meaning, and the shallow-copy rule behind spread is the source of many "why did my state not update?" bugs.
Destructuring arrays
Destructuring pulls values out of an array or object into variables in one line. For arrays, position decides which value goes where.
Press Run (⌘ Enter) to see what happens.You have seen this pattern already: React's const [count, setCount] = useState(0) is array destructuring of a two-element array. Python developers will recognise it as tuple unpacking (x, y = point), with ...rest playing the role of *rest.
Destructuring objects
For objects, the property name decides which value you get, so order does not matter.
Press Run (⌘ Enter) to see what happens.The rename syntax trips people up: in { name: fullName } the left side is the property to read and the right side is the new variable. It reads like an object literal but works in the opposite direction.
Destructuring in function parameters is where it shines. It gives you named arguments with defaults, in any order:
Press Run (⌘ Enter) to see what happens.Every React component that takes props works this way: function Card({ title, children }).
What does this print?
const settings = { theme: "dark", size: 14 };
const { theme: mode, size = 12, lang = "en" } = settings;
console.log(mode, size, lang);const order = { id: 1 };
const { shipping: { city } } = order;Spread: copying and merging
The spread syntax ... expands an array or object in place. It looks like rest but does the opposite: rest collects into one variable, spread expands into many slots.
Press Run (⌘ Enter) to see what happens.When the same key appears twice, the later one wins. That is why { ...defaults, ...overrides } is the standard way to apply settings, and why { ...state, loading: true } is how React code updates one field without mutating.
Spread is shallow
Spread copies only the top level. Nested objects and arrays are not copied; the new object points to the same inner objects as the old one.
The object holds a string and a reference to a separate array, shown as A.
What does this print?
const original = { name: "Sam", tags: ["admin"] };
const copy = { ...original };
copy.name = "Leo";
copy.tags.push("editor");
console.log(original.name, original.tags.length);To copy nested data, either spread every level you change ({ ...user, address: { ...user.address, city: "York" } }) or use structuredClone(obj), a built-in deep copy available in all modern browsers and Node 17+.
... a rest (collecting) and not a spread (expanding)?Rest parameters vs arguments
The quiz above showed ... in a parameter list collecting leftovers. That is a rest parameter, and it replaced an older feature you will still meet in legacy code and library source: the arguments object.
Press Run (⌘ Enter) to see what happens.The differences that matter:
argumentsis array-like, not an array. It haslengthand indexes but nomaporreduce, so old code is full ofArray.prototype.slice.call(arguments). A rest parameter is a real array.- Arrow functions do not have their own
arguments. Inside an arrow,argumentsrefers to the enclosing regular function's, as the last line shows. That surprises people who convert afunctionto an arrow and see the wrong values. - Rest is explicit.
log(level, ...parts)says in the signature thatlevelis required and the rest are extras.argumentshides the real arity. - Rest must be last, and there can only be one.
function f(...a, b)is a SyntaxError. fn.lengthignores the rest parameter (and anything with a default).log.lengthis1. Libraries that inspectlength, such as some middleware routers deciding whether a handler takesnext, can behave differently if you change a signature to use rest or defaults.
In TypeScript, a rest parameter is typed as an array or tuple: (...parts: string[]). You will see the tuple form, (...args: [id: string, retries?: number]), in typed event emitters and wrappers. Use rest everywhere in new code; reach for arguments only when reading old code.
Deep copies: structuredClone and its limits
You saw that spread is shallow and that structuredClone makes a deep copy. Before structuredClone arrived (2022, now in every browser, Node and worker), the standard trick was JSON.parse(JSON.stringify(obj)). You will still find it in many codebases, and it quietly corrupts data:
Press Run (⌘ Enter) to see what happens.The JSON round trip turned the Date into a string, the Set into {}, dropped the undefined field and turned NaN into null. It would have thrown on the cycle, which is why it had to be removed first. structuredClone keeps all of those, including the cycle.
It has its own limits, and they come from what it was built for: copying data between windows and workers, where code cannot travel.
| Value | What structuredClone does |
|---|---|
| Plain objects, arrays, primitives | Deep copy |
Date, Map, Set, RegExp, typed arrays, Blob, Error | Deep copy with the right type |
| Cycles and shared references | Preserved: the copy has the same shape |
| Functions, DOM nodes | Throws DataCloneError |
| Class instances | Copied as plain objects: own data survives, the prototype (and so every method) is lost |
| Getters | Read once; the copy has a plain data property |
| Symbol keys, non-enumerable properties | Dropped |
The class-instance row is the one that bites. If your state holds class instances, a deep clone gives you objects that look right in the debugger and then throw "format is not a function". Either keep state as plain data (the usual advice in React and Redux) or give the class its own clone() method.
Also think about whether you need a deep copy at all. Cloning a large object on every change is slow and throws away the cheap reference checks that UI libraries rely on. The next section is usually the better answer.
Immutable updates of nested state
React, Redux, Zustand and most state libraries decide what changed by comparing references: is next.cart the same object as state.cart? If you mutate in place, the reference stays the same, and the screen does not update. If you deep clone everything, every reference changes, and everything re-renders. The pattern seniors use sits in between: copy only the path you change, and share everything else. This is called structural sharing.
Press Run (⌘ Enter) to see what happens.Only the objects on the path to the change are new: the root, cart, the items array and the tee item. Four small copies.
The recipes, which you will write constantly:
| Change | Expression |
|---|---|
| Set a nested field | { ...s, user: { ...s.user, name } } |
| Update one array item | items.map((i) => (i.id === id ? { ...i, qty } : i)) |
| Add an item | [...items, newItem] |
| Remove an item | items.filter((i) => i.id !== id) |
| Replace by index | items.with(index, newItem) |
Past three levels deep, the spreads get hard to read and easy to get wrong (forget one ... and you drop every sibling field). Two common answers: flatten the state (store items in an object keyed by id instead of nested arrays), or use Immer, which lets you write mutating-looking code on a draft and produces a structurally shared copy for you. Redux Toolkit uses Immer inside its reducers. You will see both in the React course.
What does this print?
const a = { meta: { v: 1 }, list: [{ id: 1 }, { id: 2 }] };
const b = { ...a, list: a.list.map((x) => (x.id === 2 ? { ...x, done: true } : x)) };
console.log(b.meta === a.meta, b.list === a.list, b.list[0] === a.list[0]);Copying array methods: toSorted, toReversed, toSpliced, with
Arrays and Objects introduced toSorted and its siblings. In the context of immutable updates they are the missing pieces, because four of the most useful array methods mutate:
| Mutates the original | Returns a new array (ES2023) |
|---|---|
arr.sort(fn) | arr.toSorted(fn) |
arr.reverse() | arr.toReversed() |
arr.splice(start, count, ...items) | arr.toSpliced(start, count, ...items) |
arr[i] = value | arr.with(i, value) |
Press Run (⌘ Enter) to see what happens.Details worth knowing:
withthrowsRangeErrorfor an index outside the array. Plain assignmentarr[5] = 1silently grows the array with holes instead. For immutable updates the error is a feature.toSplicedreturns the new array, not the removed items. That is the opposite ofsplice, which returns what it removed. Mixing them up is a common bug when converting code.- They are still shallow.
toSortedgives you a new array holding the same objects. Sorting is safe; mutating an item afterwards still affects the original. - Holes become
undefined.[1, , 3].toSorted()gives[1, 3, undefined]. You rarely meet sparse arrays, but this is where they surface. - They are in all current browsers and Node 20+. If a code base targets older environments,
[...arr].sort()is the classic equivalent. TypeScript needslibto includeES2023or later to know about them; current defaults already do.
Match each operation to the value it returns.
Optional chaining: ?.
Reading a property of undefined or null throws a TypeError. API data often has missing pieces, so before 2020 code looked like user && user.address && user.address.city.
Optional chaining (?., ES2020) short-circuits: if the value on its left is null or undefined, the whole expression returns undefined instead of throwing.
Press Run (⌘ Enter) to see what happens.It comes in three shapes: obj?.prop, obj?.[key] and fn?.() (call only if the function exists). Do not sprinkle it everywhere, though. If a value should always exist, a loud error is better than a silent undefined that breaks something three files away.
Nullish coalescing: ?? vs ||
To supply a fallback, older code used ||: const port = input || 3000. The problem is that || falls back for any falsy value, including 0, "" and false, which are often perfectly valid.
The nullish coalescing operator ?? falls back only for null or undefined.
Press Run (⌘ Enter) to see what happens.?? pairs naturally with ?.: user?.settings?.volume ?? 50 reads safely and falls back only when the value is truly absent. There is also ??=, which assigns only when the variable is null or undefined: options.retries ??= 3.
What does each expression evaluate to?
Describe a user safely
API data is messy. Write describeUser(user) that returns "<name> (<age>) from <city>", where:
namefalls back to"Anonymous"if it isnullor missingagefalls back to"age unknown"if missing, but0is a valid agecitycomes fromuser.address.cityand falls back to"nowhere".addressitself may be missing ornull.
describeUser({ name: "Ada", age: 36, address: { city: "London" } }); // "Ada (36) from London"
describeUser({ name: "Leo", age: 0, address: null }); // "Leo (0) from nowhere"
describeUser({}); // "Anonymous (age unknown) from nowhere"Deep merge settings
Spread only merges the top level. Write deepMerge(target, source) that returns a new object:
- Keys from both objects are included.
- When both values for a key are plain objects, merge them recursively.
- Otherwise the value from
sourcewins (arrays,nulland primitives are replaced, not merged). - Neither input may be mutated.
deepMerge({ a: 1, ui: { theme: "light", size: 14 } }, { ui: { size: 16 } });
// { a: 1, ui: { theme: "light", size: 16 } }Treat a value as a plain object when it is not null, has typeof "object", and is not an array.
- destructuring
- Unpacking array items (by position) or object properties (by name) into variables in one statement.
- rest (...)
- On the left of
=or in parameters: collects the remaining items or properties into a new array or object. - spread (...)
- In a literal or call: expands an array or object. Later keys win when merging.
- shallow copy
- A copy of the top level only. Nested objects are still shared with the original.
- optional chaining (?.)
- Returns
undefinedinstead of throwing when the left side isnullorundefined. - nullish coalescing (??)
- Falls back to the right side only when the left is
nullorundefined, unlike||. - rest parameter
...nameas the last parameter: collects the remaining arguments into a real array. Replacesarguments.- structuredClone
- Built-in deep copy that keeps Dates, Maps, Sets and cycles, but drops class prototypes and throws on functions.
- structural sharing
- An immutable update that copies only the objects on the changed path and reuses every other branch.