JavaScript · Lesson 8
Modern Syntax: Destructuring, Spread and Friends
The syntax every modern codebase is written in (destructuring, spread and rest, optional chaining, nullish coalescing, logical assignment, template literals and tagged templates, shorthand and computed properties) plus how modules work.
In short
- Destructuring: property on the left, variable on the right
- Defaults apply to
undefinedonly, notnull - Spread is shallow: copy every level you change
??for defaults;||replaces every falsy value?.stops atnullorundefined;??=assigns only when missing- Tagged templates get strings and values separately
Open any React component, Angular service or Node handler written in the last few years and most of the
lines use syntax from ES2015 to ES2021: const { data = [] } = response, { ...state, loading: false },
user?.address?.city ?? 'unknown', `Hello ${name}`. None of it adds new abilities. It's shorthand
for code you could write longhand. But each piece has one rule that people get wrong, and those rules are
what interviews and code reviews probe:
- Destructuring defaults apply to
undefinedonly, not tonull. - Spread copies one level deep.
||treats0,''andfalseas missing.??doesn't.- Optional chaining stops at
nullorundefinedand givesundefined. It doesn't hide other errors.
This lesson goes through each feature with the rule that matters. Every snippet has a ▶ Try button, except the module examples at the end, which need real files.
Destructuring objects
Destructuring pulls values out of an object into variables, by property name:
const response = { id: 7, attributes: { name: 'Ann', email: 'ann@example.com' }, meta: null };
const { id, attributes } = response; // same names as the properties
const { attributes: { name: userName } } = response; // nested, and renamed to userName
const { role = 'viewer' } = response; // a default for a missing property
const { id: userId, ...rest } = response; // rename, and collect the rest
console.log(id, attributes.email, userName, role, userId, Object.keys(rest));
The pieces:
{ id }readsresponse.idinto a variableid.{ id: userId }readsresponse.idinto a variable calleduserId. The left side of the colon is the property, the right side is the variable. People read it backwards at first.{ role = 'viewer' }uses the default when the property is missing.{ ...rest }collects every remaining own enumerable property into a new object. It must come last.- Nesting follows the shape of the data:
{ attributes: { name } }doesn't create anattributesvariable, onlyname.
Defaults apply to undefined only
This is the rule that causes production bugs. A default is used when the value is undefined, which
includes a missing property. It is not used for null.
const fromApi = { page: null, size: undefined, tags: null };
const { page = 1, size = 20 } = fromApi;
console.log(page, size); // null 20
try {
const { tags: [firstTag] = [] } = fromApi; // the default doesn't kick in for null
} catch (e) {
console.log(e.constructor.name, e.message);
}
JSON can't carry undefined, so APIs send null for "no value". A default in a destructuring pattern won't
protect you from that. When null is possible, use ?? instead: const tags = fromApi.tags ?? [].
Defaults are evaluated lazily, only when needed, and can refer to earlier variables:
const { width, height = width } = box.
Destructuring arrays
Array destructuring goes by position, and works with anything iterable: strings, Maps, Sets,
Object.entries(...).
const [first, , third = 'c', ...others] = ['a', 'b', undefined, 'd', 'e'];
console.log(first, third, others); // skip with an empty slot, default, rest
let a = 1;
let b = 2;
[a, b] = [b, a]; // swap without a temp variable
console.log(a, b);
const scores = { ann: 9, bob: 7 };
for (const [name, score] of Object.entries(scores)) console.log(`${name}: ${score}`);
const [, year, month] = /(\d{4})-(\d{2})/.exec('2026-10-20');
console.log(year, month);
React's const [count, setCount] = useState(0) is array destructuring: the hook returns a two-item array,
and you choose the names. That's why hooks return arrays and not objects.
Destructuring parameters: the options object
Destructuring in a parameter list is how JavaScript does named, optional arguments:
function createClient(baseUrl, { timeoutMs = 5000, retries = 2, headers = {} } = {}) {
return { baseUrl, timeoutMs, retries, headers };
}
console.log(createClient('/api'));
console.log(createClient('/api', { retries: 0 }));
The = {} at the end is the default for the whole second argument. Without it, createClient('/api')
tries to destructure undefined and throws a TypeError. Callers can pass the options in any order, skip
any of them, and retries: 0 works because 0 isn't undefined.
Spread and rest
The same three dots do two opposite jobs:
- Rest (on the left, or in parameters) collects items:
function log(...args),const [x, ...others] = list. - Spread (on the right) expands items:
[...a, ...b],{ ...defaults, ...overrides },Math.max(...numbers).
const defaults = { theme: 'light', fontSize: 14, beta: false };
const saved = { fontSize: 16, beta: undefined };
const settings = { ...defaults, ...saved }; // later properties win
console.log(settings);
const merged = [...[1, 2], ...new Set([2, 3])];
console.log(merged, Math.max(...merged));
Notice beta: spreading { beta: undefined } overwrites the default with undefined. Spread copies
every own property, including ones whose value is undefined. If "undefined means not set" in your data,
filter those keys out first, or use ?? property by property.
Spread is shallow
const state = { user: { name: 'Ann' }, tags: ['a'] };
const copy = { ...state };
copy.user.name = 'Bob'; // same nested object
copy.tags = [...copy.tags, 'b']; // replaced, so state.tags is untouched
console.log(state.user.name, state.tags);
Spread makes a new outer object, but its properties point at the same nested objects. To update nested state immutably, spread every level on the path to the change:
const state = { user: { name: 'Ann', address: { city: 'Leeds' } }, loading: true };
const next = {
...state,
user: { ...state.user, address: { ...state.user.address, city: 'York' } },
};
console.log(state.user.address.city, next.user.address.city, next.loading);
That's exactly what reducers and signal update functions look like. When it gets deep, use
structuredClone for a full copy, or a library like Immer.
Other spread rules worth knowing:
- In an object, spreading
nullorundefinedis allowed and adds nothing:{ ...maybeExtra }. In an array or a call, it throws, becausenullisn't iterable. - Object spread runs getters and copies their values. It doesn't copy the prototype, so spreading a class instance gives a plain object without its methods.
{ ...'hi' }is{ 0: 'h', 1: 'i' }. Strings spread into characters.
Optional chaining: ?.
a?.b means "if a is null or undefined, stop here and give undefined; otherwise read a.b".
const order = { customer: { address: null }, items: [], notify: undefined };
console.log(order.customer?.address?.city); // undefined, no error
console.log(order.items?.[0]?.sku); // with brackets
console.log(order.notify?.('shipped')); // calls it only if it isn't null or undefined
console.log(order.missing?.deeply.nested.path); // short-circuits the whole chain
try {
console.log(order.customer.address.city); // no ?. here
} catch (e) {
console.log(e.message);
}
- It short-circuits the whole chain to its right:
a?.b.c.ddoesn't throw whenaisnull. - It only checks
nullandundefined.0?.toFixed(1)works;''?.lengthis0. - It can't be used on the left of
=:a?.b = 1is a syntax error. - Don't sprinkle it everywhere. If
order.customershould always exist,order.customer?.namehides a bug that a clear error would have shown. Use it where a value is genuinely optional.
Nullish coalescing: ?? vs ||
a ?? b gives b only when a is null or undefined. a || b gives b whenever a is falsy:
0, '', false, NaN, null or undefined.
const config = { retries: 0, prefix: '', verbose: false, timeout: null };
console.log(config.retries || 3, config.retries ?? 3);
console.log(JSON.stringify(config.prefix || '/api'), JSON.stringify(config.prefix ?? '/api'));
console.log(config.verbose || true, config.verbose ?? true);
console.log(config.timeout ?? 5000);
For defaults, ?? is almost always what you mean. || turns a deliberate 0, empty string or false
into the default, which is the classic "I set retries to 0 and it still retries three times" bug. Use ||
only when every falsy value really should be replaced, for example an empty display name.
JavaScript refuses to guess precedence between them: a || b ?? c is a syntax error. Add parentheses.
Logical assignment: ??=, ||=, &&=
Each one assigns only when the matching operator would pick the right-hand side:
const cache = {};
(cache.users ??= []).push('ann'); // create the array the first time only
(cache.users ??= []).push('bob');
console.log(cache.users);
const form = { name: '', count: 0 };
form.name ||= 'Untitled'; // '' is falsy, so it's replaced
form.count ??= 10; // 0 isn't nullish, so it's kept
console.log(form);
let session = { token: 'abc' };
session &&= { ...session, refreshedAt: 'now' }; // only if there is a session
console.log(session);
They short-circuit: x ??= expensive() doesn't call expensive() when x already has a value, and
doesn't assign at all, so a setter isn't triggered. map[key] ??= [] is the idiom for "get or create",
the same as TryAdd or GetValueOrDefault patterns in C#.
Template literals and tagged templates
Backtick strings can span lines and embed any expression with ${...}:
const user = { name: 'Ann', items: 3 };
const message = `Hi ${user.name},
you have ${user.items} item${user.items === 1 ? '' : 's'} in your basket.`;
console.log(message);
console.log(`${[1, 2]} | ${{}} | ${null}`); // values are converted with String()
A tagged template puts a function name before the backticks. The function receives the literal pieces and the values separately, and returns whatever it likes, not necessarily a string:
function show(strings, ...values) {
console.log(strings, values);
return strings.reduce((out, s, i) => out + s + (i < values.length ? `[${values[i]}]` : ''), '');
}
const qty = 3;
console.log(show`Ordered ${qty} of ${'widget'}.`);
There's always one more string than values: here ['Ordered ', ' of ', '.'] and [3, 'widget']. The
strings array is frozen and has a raw property with the text before escape sequences were processed,
which is what String.raw returns: String.raw`C:\new` keeps the backslash.
Tags are how libraries safely mix code and data. sql`...` tags turn values into query parameters,
html`...` tags escape values (the HTML-escaping tagged template exercise), Lit renders templates with
them, and gql parses GraphQL. The tag sees which parts you wrote and which came from variables, so it can
treat them differently. A plain template literal can't.
Shorthand and computed properties
const name = 'Ann';
const field = 'email';
const version = 2;
const user = {
name, // shorthand for name: name
[field]: 'ann@example.com', // computed key
[`v${version}Enabled`]: true,
greet() { // method shorthand
return `Hi, ${this.name}`;
},
};
console.log(user, user.greet());
const { [field]: value } = user; // computed keys work in destructuring too
console.log(value);
Computed keys power the common "update one field" handler: setForm((f) => ({ ...f, [e.target.name]: e.target.value })).
Combined with rest, they remove a key without mutating: const { [key]: _removed, ...without } = obj.
Numeric separators
Underscores make long numbers readable. They're ignored by the engine:
const budget = 1_250_000;
const timeoutMs = 30_000;
const mask = 0b1111_0000;
console.log(budget, timeoutMs, mask, Number('1_000'));
They're only for literals in code. Number('1_000') and JSON.parse don't accept them (you get NaN
and a syntax error), and you can't start, end or double them (1__000 is a syntax error).
Modules: ESM and CommonJS
The lab runs each exercise as one file, so these examples can't run here, but you'll meet modules in every real project.
ES modules (ESM) are the standard: browsers, Vite, Angular, and Node with "type": "module" or .mjs
files.
// not runnable here: math.js
export const TAX_RATE = 0.2;
export function addTax(amount) {
return amount * (1 + TAX_RATE);
}
export default function format(amount) {
return `£${amount.toFixed(2)}`;
}
// not runnable here: app.js
import format, { addTax, TAX_RATE as rate } from './math.js';
import * as math from './math.js';
console.log(format(addTax(10)), rate, math.TAX_RATE);
const { heavyChart } = await import('./chart.js'); // dynamic import: loads on demand
- Named exports (
export const,import { addTax }) must be imported by their exact name (renaming withasis allowed). Editors can auto-import them and bundlers can drop unused ones (tree shaking). Most style guides prefer them. - A default export is imported under any name you choose. That flexibility means the same thing ends up with different names in different files. React components and Angular lazy routes often use default exports.
- Imports are hoisted and resolved before any code in the file runs. Module code runs once, the first
time it's imported, and always in strict mode. Top-level
awaitis allowed. - Imports are live bindings, not copies. If the exporting module reassigns an exported
let, importers see the new value. You can't assign to an import yourself: it's read-only.
// not runnable here: counter.js and main.js
// counter.js
export let count = 0;
export function increment() { count++; }
// main.js
import { count, increment } from './counter.js';
increment();
console.log(count); // 1: a live view of counter.js's variable
count = 5; // TypeError: assignment to constant variable
CommonJS (CJS) is Node's original system, still in many packages and older services:
// not runnable here: CommonJS
const { addTax } = require('./math'); // synchronous, can be called anywhere
module.exports = { format }; // exports are a plain object
exports.helper = () => {}; // a shortcut that adds to module.exports
The differences that bite: require is synchronous and runs wherever you call it, while import is static
and resolved up front. require gives you the module's exports object, not live
bindings to its variables. ESM in Node needs file extensions in relative imports ('./math.js'), and has no __dirname
(use import.meta.dirname or import.meta.url). In recent Node versions (22.12 and later), require can load most ES modules too, but
mixing the two systems in one package is still the most common source of "it works in tests but not in
the build" problems.
Coming from C# or TypeScript
Side note
- Destructuring is like C# deconstruction (
var (x, y) = point;) but by property name, and it works on any object without aDeconstructmethod. C# 8 property patterns are the closest match. - Spread on objects is like a
withexpression on a C# record (order with { Status = "paid" }): a shallow copy with some properties changed. ?.and??behave like C#'s, and??=is C# 8's. Unlike C#, JavaScript has two "empty" values,nullandundefined, and?./??treat both the same.- Options objects replace C# optional and named parameters:
send(msg, { retries: 0 })instead ofSend(msg, retries: 0). - TypeScript adds types to all of this (
function f({ a = 1 }: { a?: number } = {})) but the runtime rules are identical. In particular,?:in a TypeScript type allowsundefined, notnull, which matches the destructuring default rule.
In real codebases
Side note
- API boundaries: destructure and normalise once, where the data comes in (
const { data: { items = [] } = {} } = res), so the rest of the app never seesnullwhere it expects an array. The Normalise an API response exercise does this. - React: props destructuring with defaults (
function Button({ size = 'md', ...rest })), state updates with spread,useStatewith array destructuring, and computed keys in form handlers. - Angular: spread in signal and NgRx updates (
state.update((s) => ({ ...s, loading: true }))),?.and??in templates, which use the same operators. - Config:
??for every default, because0,falseand''are valid settings. - Lint rules to know:
prefer-destructuring,@typescript-eslint/prefer-nullish-coalescing(flags||where??was probably meant) and@typescript-eslint/prefer-optional-chain.
The exercises
- Reshape rows (easy): array destructuring, rest, swapping and renaming keys.
- Safe config reader (easy):
??and??=where0,''andfalseare valid values. - Normalise an API response (medium): nested destructuring with defaults, and the
nulltrap. - Request options (medium): an options-object parameter with defaults, and rest to catch typos.
- HTML-escaping tagged template (medium): a tag function that escapes values but not trusted markup.
- Immutable get and set by path (hard): optional chaining and nested spread, one level at a time.
- JSON Merge Patch (hard): recursive spread, computed keys and rest to delete properties.
Practise this lesson
In the app: a short video, 7 exercises checked by real tests and a 12-question concept check. Free with a GitHub account.
Open in the app