Skip to content

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 ??.

22 min read0/7 questions

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.

JavaScript
const point = [3, 7, 9]; const [x, y] = point; // take the first twoconst [, , z] = point; // skip with commasconst [first, ...others] = point; // rest collects the remainderconst [a, b, c, d = 0] = point; // default when the slot is undefined console.log(x, y, z);console.log(first, others);console.log(d); // Swap two variables without a templet left = 1;let right = 2;[left, right] = [right, left];console.log(left, right);
Output
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.

JavaScript
const user = { id: 7, name: "Priya", address: { city: "Leeds", zip: "LS1" },}; const { name, id } = user; // pick properties by nameconst { name: fullName } = user; // rename: take name, call it fullNameconst { role = "viewer" } = user; // default for a missing propertyconst { address: { city } } = user; // nested: reach inside addressconst { id: userId, ...profile } = user; // rest: everything except id console.log(name, id, fullName, role, city);console.log(profile);
Output
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:

JavaScript
function createButton({ label, size = "md", disabled = false }) { return `<button class="${size}"${disabled ? " disabled" : ""}>${label}</button>`;} console.log(createButton({ label: "Save" }));console.log(createButton({ disabled: true, label: "Send", size: "lg" }));
Output
Press Run (⌘ Enter) to see what happens.

Every React component that takes props works this way: function Card({ title, children }).

Predict the outputJavaScript

What does this print?

const settings = { theme: "dark", size: 14 };
const { theme: mode, size = 12, lang = "en" } = settings;
console.log(mode, size, lang);
Need a nudge? Hints walk you through it.
Quick check
What happens here?
const order = { id: 1 };
const { shipping: { city } } = order;
Need a nudge? A hint rules out a wrong answer.

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.

JavaScript
const base = [1, 2, 3];const more = [...base, 4, 5]; // copy and addconst merged = [...base, ...[9, 8]];console.log(more, merged);console.log(Math.max(...base)); // array to separate arguments const defaults = { theme: "light", fontSize: 14, beta: false };const userPrefs = { theme: "dark" };const config = { ...defaults, ...userPrefs }; // later keys winconsole.log(config); const updated = { ...config, fontSize: 16 }; // copy with one changeconsole.log(updated.fontSize, config.fontSize);
Output
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.

What a shallow copy shares
const original = { name: "Sam", tags: ["admin"] };
NamesObjects in memoryoriginalobject{ name: 'Sam', tags: → A }array A['admin']

The object holds a string and a reference to a separate array, shown as A.

1/4
Predict the outputJavaScript

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);
Need a nudge? Hints walk you through it.

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+.

Quick check
In which line is ... a rest (collecting) and not a spread (expanding)?
Need a nudge? A hint rules out a wrong answer.

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.

JavaScript
function oldSum() { console.log(Array.isArray(arguments), arguments.length); return Array.prototype.reduce.call(arguments, (a, b) => a + b, 0);} function sum(...nums) { console.log(Array.isArray(nums), nums.length); return nums.reduce((a, b) => a + b, 0);} console.log(oldSum(1, 2, 3), sum(1, 2, 3)); function log(level, ...parts) { return `[${level}] ${parts.join(" ")}`;}console.log(log("warn", "disk", "at", "91%"));console.log(sum.length, log.length, oldSum.length); const outer = function () { const arrow = () => arguments[0]; // arrows have no arguments of their own return arrow("ignored");};console.log(outer("from outer"));
Output
Press Run (⌘ Enter) to see what happens.

The differences that matter:

  • arguments is array-like, not an array. It has length and indexes but no map or reduce, so old code is full of Array.prototype.slice.call(arguments). A rest parameter is a real array.
  • Arrow functions do not have their own arguments. Inside an arrow, arguments refers to the enclosing regular function's, as the last line shows. That surprises people who convert a function to an arrow and see the wrong values.
  • Rest is explicit. log(level, ...parts) says in the signature that level is required and the rest are extras. arguments hides the real arity.
  • Rest must be last, and there can only be one. function f(...a, b) is a SyntaxError.
  • fn.length ignores the rest parameter (and anything with a default). log.length is 1. Libraries that inspect length, such as some middleware routers deciding whether a handler takes next, 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:

JavaScript
const order = { id: 1, placedAt: new Date("2026-10-22T09:30:00Z"), tags: new Set(["gift"]), notes: undefined, total: NaN,};order.self = order; // a cycle const viaJson = JSON.parse(JSON.stringify({ ...order, self: null }));console.log(typeof viaJson.placedAt, viaJson.tags, "notes" in viaJson, viaJson.total); const clone = structuredClone(order);console.log(clone.placedAt instanceof Date, clone.tags.has("gift"), "notes" in clone, clone.total);console.log(clone.self === clone, clone.placedAt === order.placedAt); class Money { constructor(cents) { this.cents = cents; } format() { return (this.cents / 100).toFixed(2); }}const copy = structuredClone({ price: new Money(1299) });console.log(copy.price instanceof Money, copy.price.cents, typeof copy.price.format); try { structuredClone({ onClick: () => {} });} catch (e) { console.log(e.name);}
Output
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.

ValueWhat structuredClone does
Plain objects, arrays, primitivesDeep copy
Date, Map, Set, RegExp, typed arrays, Blob, ErrorDeep copy with the right type
Cycles and shared referencesPreserved: the copy has the same shape
Functions, DOM nodesThrows DataCloneError
Class instancesCopied as plain objects: own data survives, the prototype (and so every method) is lost
GettersRead once; the copy has a plain data property
Symbol keys, non-enumerable propertiesDropped

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.

JavaScript
const state = { user: { name: "Priya", prefs: { theme: "dark" } }, cart: { items: [ { id: "mug", qty: 1 }, { id: "tee", qty: 2 }, ], },}; // Change one item's qty: copy every level on the path, share the restconst next = { ...state, cart: { ...state.cart, items: state.cart.items.map((item) => item.id === "tee" ? { ...item, qty: item.qty + 1 } : item ), },}; console.log(next.cart.items[1].qty, state.cart.items[1].qty); // new vs oldconsole.log(next === state, next.cart === state.cart); // changed path: new objectsconsole.log(next.user === state.user); // untouched branch: sharedconsole.log(next.cart.items[0] === state.cart.items[0]); // untouched item: shared // Add and remove without mutatingconst added = { ...next, cart: { ...next.cart, items: [...next.cart.items, { id: "pen", qty: 1 }] } };const removed = { ...added, cart: { ...added.cart, items: added.cart.items.filter((i) => i.id !== "mug") } };console.log(removed.cart.items.map((i) => `${i.id}x${i.qty}`).join(", "));console.log(state.cart.items.length, "items in the original");
Output
Press Run (⌘ Enter) to see what happens.
Structural sharing after changing tee's qty
nextnewprefssharedusershared with statemugsharedteenew object, qty 3itemsnew arraycartnewroot

Only the objects on the path to the change are new: the root, cart, the items array and the tee item. Four small copies.

1/3

The recipes, which you will write constantly:

ChangeExpression
Set a nested field{ ...s, user: { ...s.user, name } }
Update one array itemitems.map((i) => (i.id === id ? { ...i, qty } : i))
Add an item[...items, newItem]
Remove an itemitems.filter((i) => i.id !== id)
Replace by indexitems.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.

Predict the outputJavaScript

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]);
Need a nudge? Hints walk you through it.

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 originalReturns 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] = valuearr.with(i, value)
JavaScript
const scores = [40, 10, 30]; console.log(scores.toSorted((a, b) => a - b)); // sorted copyconsole.log(scores.with(1, 15)); // replace index 1console.log(scores.with(-1, 0)); // negative index counts from the endconsole.log(scores.toSpliced(0, 1)); // remove the firstconsole.log(scores.toSpliced(1, 0, 99)); // insert at index 1console.log(scores); // untouched try { scores.with(5, 1);} catch (e) { console.log(e.name); // out of range throws, unlike arr[5] = 1}
Output
Press Run (⌘ Enter) to see what happens.

Details worth knowing:

  • with throws RangeError for an index outside the array. Plain assignment arr[5] = 1 silently grows the array with holes instead. For immutable updates the error is a feature.
  • toSpliced returns the new array, not the removed items. That is the opposite of splice, which returns what it removed. Mixing them up is a common bug when converting code.
  • They are still shallow. toSorted gives 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 needs lib to include ES2023 or later to know about them; current defaults already do.
Match the pairs0/5 matched

Match each operation to the value it returns.

Choose an item, then its match on the other side.

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.

JavaScript
const users = [ { name: "Ada", address: { city: "London" }, greet: () => "hello" }, { name: "Sam" },]; for (const u of users) { console.log(u.address?.city, u.greet?.());} const list = null;console.log(list?.[0]); // works with brackets too
Output
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.

JavaScript
const settings = { volume: 0, nickname: "", notifications: false }; console.log(settings.volume || 50); // 50: wrong, 0 was a real choiceconsole.log(settings.volume ?? 50); // 0: correct console.log(JSON.stringify(settings.nickname || "anonymous"));console.log(JSON.stringify(settings.nickname ?? "anonymous")); // the empty string survives console.log(settings.missing ?? "default");
Output
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.

Match the pairs0/5 matched

What does each expression evaluate to?

Choose an item, then its match on the other side.
ChallengeEasy

Describe a user safely

API data is messy. Write describeUser(user) that returns "<name> (<age>) from <city>", where:

  • name falls back to "Anonymous" if it is null or missing
  • age falls back to "age unknown" if missing, but 0 is a valid age
  • city comes from user.address.city and falls back to "nowhere". address itself may be missing or null.
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"
JavaScript
function describeUser(user) { // Destructure what you need, then use ?. and ?? for the fallbacks. return "";}
ChallengeMedium

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 source wins (arrays, null and 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.

JavaScript
function deepMerge(target, source) { // Start from a shallow copy of target, then walk source's keys. return {};}
Key terms
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 undefined instead of throwing when the left side is null or undefined.
nullish coalescing (??)
Falls back to the right side only when the left is null or undefined, unlike ||.
rest parameter
...name as the last parameter: collects the remaining arguments into a real array. Replaces arguments.
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.