Sub topic 13
When Defaults Don't Apply and Destructuring Throws
This chapter assumes you already know basic array and object destructuring, default values in patterns, nested patterns, and parameter destructuring. It covers the two kinds of surprises those features cause. Sometimes a default you expected is not used. Sometimes the destructuring line throws an error before any of your code runs.
Both come from two rules in the language:
- A default is used only when the value it would replace is exactly
undefined. - Destructuring has to read from the value on the right-hand side. If that value is
nullorundefined(or is not iterable, for array patterns), the read fails with aTypeError.
Defaults Trigger Only on `undefined`
A default in a pattern checks value === undefined. It does not test whether the value is falsy or whether it is "empty". The values null, 0, '', false, and NaN are all real values, so they pass through unchanged.
const config = {
retries: 0,
label: '',
verbose: false,
timeout: null,
ratio: NaN,
mode: undefined,
};
const {
retries = 3,
label = 'none',
verbose = true,
timeout = 1000,
ratio = 1,
mode = 'auto',
missing = 'fallback',
} = config;
console.log(retries); // 0
console.log(label); // ''
console.log(verbose); // false
console.log(timeout); // null
console.log(ratio); // NaN
console.log(mode); // 'auto' (explicit undefined)
console.log(missing); // 'fallback' (absent property reads as undefined)A missing property and a property set to undefined look the same to the pattern. Reading either one gives undefined, so the default applies in both cases.
The null case causes the most bugs. JSON has no undefined, so APIs and databases represent "no value" as null. A pattern like { timeout = 1000 } gives you null for those records, and code later on may treat null as a timeout of zero.
Choosing Between a Pattern Default, `??`, and `||`
If you want null to fall back as well, destructure without a default and apply the nullish coalescing operator ?? afterwards:
const record = { timeout: null, retries: 0 };
const { timeout: rawTimeout, retries: rawRetries } = record;
const timeout = rawTimeout ?? 1000;
const retries = rawRetries || 3;
console.log(timeout); // 1000 (null replaced)
console.log(retries); // 3 (0 replaced: || treats 0 as falsy)| Technique | Replaces `undefined` | Replaces `null` | Replaces `0`, `''`, `false`, `NaN` | Column | Column |
|---|---|---|---|---|---|
| Pattern default `{ x = d }` | Yes | No | No | ||
| `x ?? d` | Yes | Yes | No | ||
| `x \ | \ | d` | Yes | Yes | Yes |
Use ?? when 0, '', or false are legitimate values. Use || only when every falsy value should mean "use the default". The retries line above shows how || can quietly turn a deliberate 0 into 3.
Defaults Are Evaluated Lazily, Left to Right
A default expression runs only when it is needed. If the value is present, the expression is never evaluated. This matters when the default has side effects or is expensive to compute.
let calls = 0;
function makeId() {
calls += 1;
return `id-${calls}`;
}
const [a = makeId()] = ['given'];
const [b = makeId()] = [];
console.log(a, b); // 'given' 'id-1'
console.log(calls); // 1 (makeId ran only once)Defaults are evaluated in order, so a later default can refer to a binding declared earlier in the same pattern. An earlier default cannot refer to a later binding. That binding is still in its temporal dead zone (the period before a let or const binding is initialized), and reading it throws a ReferenceError:
const [width = 10, height = width * 2] = [];
console.log(width, height); // 10 20
try {
const [first = second, second = 1] = [];
} catch (err) {
console.log(err instanceof ReferenceError); // true
}Destructuring `null` or `undefined` Throws
An object pattern reads properties from the source value. null and undefined have no properties, so the read throws a TypeError. An empty pattern throws too, because the check happens before any property is read.
const sources = [null, undefined];
for (const source of sources) {
try {
const { name } = source;
} catch (err) {
console.log(err instanceof TypeError); // true, twice
}
try {
const {} = source;
} catch (err) {
console.log(err instanceof TypeError); // true, twice
}
}The error message depends on the engine. V8 (Chrome and Node.js) prints something like Cannot destructure property 'name' of 'source' as it is null. Firefox phrases it differently. Don't write code that parses the message text.
Other primitives do not throw. Strings, numbers, and booleans are temporarily wrapped in their object types, so you can destructure their properties:
const { length } = 'hello';
const { toFixed } = 5;
console.log(length); // 5
console.log(typeof toFixed); // 'function'Array Patterns Need an Iterable
An array pattern does not read numbered properties. It asks the source for an iterator, so any value without a Symbol.iterator method throws a TypeError, including array-like objects:
const attempts = [null, 42, { 0: 'a', length: 1 }];
for (const source of attempts) {
try {
const [first] = source;
console.log(first);
} catch (err) {
console.log(err instanceof TypeError); // true, three times
}
}
const [ok] = Array.from({ 0: 'a', length: 1 });
console.log(ok); // 'a'Array.from turns an array-like object into a real array, and you can destructure that.
Nested Patterns: `= {}` Does Not Guard Against `null`
A nested pattern destructures again at every level, so the rules above apply at every level too. Adding = {} to an intermediate pattern protects against a missing property, but not against one set to null:
const missing = { id: 1 };
const nulled = { id: 2, shipping: null };
const { shipping: { city } = {} } = missing;
console.log(city); // undefined (default {} was used)
try {
const { shipping: { city: c } = {} } = nulled;
} catch (err) {
console.log(err instanceof TypeError); // true: null skips the default, then fails
}For data where any level might be null, optional chaining is usually clearer than a deep pattern:
const nulled = { id: 2, shipping: null };
const city = nulled.shipping?.city ?? 'unknown';
console.log(city); // 'unknown'The two approaches can also be combined. Normalize the risky level with ??, then destructure:
const nulled = { id: 2, shipping: null };
const { city = 'unknown', zip = '' } = nulled.shipping ?? {};
console.log(city, zip); // 'unknown' ''Parameters: `f()` Works, `f(null)` Does Not
A destructured parameter follows the same rules. Without a default for the whole parameter, calling the function with no argument throws. With = {}, calling it with no argument works, but passing null still throws because null skips the default.
function strict({ size = 'md' }) {
return size;
}
function guarded({ size = 'md' } = {}) {
return size;
}
function tolerant(options) {
const { size = 'md' } = options ?? {};
return size;
}
try { strict(); } catch (err) { console.log('strict():', err instanceof TypeError); } // true
console.log(guarded()); // 'md'
try { guarded(null); } catch (err) { console.log('guarded(null):', err instanceof TypeError); } // true
console.log(tolerant(null)); // 'md'
console.log(tolerant({ size: 'lg' })); // 'lg'Use the guarded form when null is a caller error that should fail loudly. Use the tolerant form at boundaries where null arrives legitimately, such as values parsed from JSON or passed in from code you don't control.
Summary of Failure Modes
| Situation | Result | Fix |
|---|---|---|
| Property is `null`, pattern has default | `null` kept | Apply `?? default` after destructuring |
| Source is `null` or `undefined` | `TypeError` | `source ?? {}` or a parameter default |
| Intermediate object is `null` | `TypeError` even with `= {}` | Optional chaining or `?? {}` at that level |
| Array pattern on a non-iterable | `TypeError` | `Array.from(arrayLike)` |
| Default refers to a later binding | `ReferenceError` | Reorder the pattern |
Exercise
What does this code print, and why? const { a = 1, b = 2, c = 3 } = { a: null, b: undefined }; console.log(a, b, c);
Show answer
It prints "null 2 3". The value of a is null, which is not undefined, so the default is skipped. The value of b is explicitly undefined, so its default 2 is used. The property c does not exist, so reading it gives undefined and its default 3 is used.
Exercise
A function is declared as function load({ url, retries = 2 } = {}) { ... }. Which of these calls throw: load(), load({}), load(null), load({ retries: null })?
Show answer
Only load(null) throws a TypeError. Calling load() uses the = {} default. load({}) destructures an empty object, so url is undefined and retries is 2. load(null) skips the parameter default because null is not undefined, then fails while destructuring null. load({ retries: null }) succeeds with retries set to null, because the inner default also applies only to undefined.
Exercise
Rewrite const { profile: { avatar = 'default.png' } = {} } = user; so that it also works when user.profile is null.
Show answer
Normalize the intermediate level before destructuring: const { avatar = 'default.png' } = user.profile ?? {}; Alternatively: const avatar = user.profile?.avatar ?? 'default.png'; The second form also replaces an avatar value of null with 'default.png'. The first form keeps a null avatar.