Sub topic 3
Supplying Default Values
Destructuring pulls a value out of an array or object and puts it in a variable. Sometimes that value isn't there. A default value is a fallback written inside the pattern with =. It gives the variable a value when the source has nothing useful at that position or property.
This chapter assumes you know how to declare variables with let and const, can work with arrays and plain objects, and have read the two earlier chapters on array destructuring (matching by position) and object destructuring (matching by property name).
The basic syntax
You add a default by writing = expression after the target name in the pattern. It works the same way in array and object patterns.
const [width = 100, height = 50] = [320];
console.log(width); // 320 (value present)
console.log(height); // 50 (no element at index 1)
const { color = 'black', size = 'M' } = { size: 'L' };
console.log(color); // 'black' (no color property)
console.log(size); // 'L' (property present)The default belongs to one target. Every variable in a pattern can have its own default, or none at all.
The one rule: defaults apply only to `undefined`
JavaScript uses the default only when the value it reads is strictly undefined. No other value triggers it. That covers three situations that look different but behave the same:
- The array has no element at that index, or the object has no property with that name.
- The element or property exists but holds
undefined. - The array has a hole at that index (a sparse array such as
[, 1]).
const [a = 'A'] = []; // missing element
const [b = 'B'] = [undefined]; // element holds undefined
const [c = 'C'] = [, 'second']; // hole at index 0
console.log(a, b, c); // 'A' 'B' 'C'
const { d = 'D' } = {}; // missing property
const { e = 'E' } = { e: undefined }; // property holds undefined
console.log(d, e); // 'D' 'E'All other values are kept as they are, including falsy values such as null, 0, '', false, and NaN. People get this wrong a lot when they expect defaults to work like ||.
const { count = 10, label = 'none', enabled = true, owner = 'root' } = {
count: 0,
label: '',
enabled: false,
owner: null,
};
console.log(count); // 0
console.log(label); // ''
console.log(enabled); // false
console.log(owner); // null| Value read from the source | Default used? |
|---|---|
| missing element or property | yes |
| `undefined` | yes |
| hole in a sparse array | yes |
| `null` | no |
| `0`, `NaN` | no |
| `''` (empty string) | no |
| `false` | no |
When you want `null` treated as missing too
APIs and JSON often use null to mean "no value". A destructuring default will not replace null. If you want it replaced, add a separate step with the nullish coalescing operator ??. That operator falls back for both null and undefined and keeps 0, '', and false.
const response = { title: null, retries: 0 };
const { title: rawTitle, retries: rawRetries } = response;
const title = rawTitle ?? 'Untitled';
const retries = rawRetries ?? 3;
console.log(title); // 'Untitled'
console.log(retries); // 0 (kept, unlike with ||)The title: rawTitle syntax renames a property. The next chapter covers it in detail. A later chapter, "When Defaults Don't Apply and Destructuring Throws", deals with null sources, which are a separate problem: destructuring null itself throws.
Defaults are evaluated lazily
The expression after = does not run every time. It runs only when the default is needed. This matters when the default calls a function that is expensive or has side effects.
function fallback(label) {
console.log(`computing default for ${label}`);
return label.toUpperCase();
}
const [m = fallback('m'), n = fallback('n')] = [10];
// logs only: computing default for n
console.log(m); // 10
console.log(n); // 'N'Because the default runs again each time it is needed, every use gets a fresh value. A default of [] or {} creates a new array or object each time, so separate destructurings never share it by accident.
const items = [{ id: 1 }, { id: 2 }];
const tagLists = [];
for (const { tags = [] } of items) {
tagLists.push(tags);
}
console.log(tagLists[0] === tagLists[1]); // false (two separate arrays)This differs from Python, where a mutable default argument is created once and shared between calls. In JavaScript the expression runs again each time.
Defaults can use earlier targets
Targets are bound from left to right. A default can therefore refer to any variable that appears earlier in the same pattern.
const [start = 0, end = start + 10] = [5];
console.log(start, end); // 5 15
const { min = 1, max = min * 100 } = {};
console.log(min, max); // 1 100The reverse doesn't work. A later variable is still in its temporal dead zone (the stretch of code before a let or const binding is initialized) while an earlier default is evaluated. Referring to it throws a ReferenceError.
try {
const [p = q, q = 1] = [];
} catch (err) {
console.log(err instanceof ReferenceError); // true
console.log(err.message); // e.g. "Cannot access 'q' before initialization"
}The exact message depends on the engine. The error type is always ReferenceError.
Defaults can also refer to variables from the surrounding scope, and they can contain any expression: function calls, template literals, ternaries, or new Date().
const DEFAULT_LOCALE = 'en-US';
const now = new Date('2026-01-01T00:00:00Z');
const { locale = DEFAULT_LOCALE, stamp = now.toISOString() } = {};
console.log(locale); // 'en-US'
console.log(stamp); // '2026-01-01T00:00:00.000Z'Inherited properties and getters count as present
Object destructuring reads each property the same way source.name does. That lookup follows the prototype chain and runs getters. So an inherited property counts as present, and its default is not used.
const { toString = 'fallback' } = {};
console.log(typeof toString); // 'function' (inherited from Object.prototype)
const proto = { mode: 'inherited' };
const child = Object.create(proto);
const { mode = 'default' } = child;
console.log(mode); // 'inherited'A getter that returns undefined does trigger the default, because the rule only looks at the value that comes back.
const config = {
get timeout() {
return undefined;
},
};
const { timeout = 3000 } = config;
console.log(timeout); // 3000Rest properties, covered in a later chapter, behave differently. They collect only own enumerable properties. Don't assume a default and a rest property see the same set of keys.
Defaults on array patterns read from iterables
Array patterns read from an iterator, not by index. A default is used when the iterator runs out before it reaches that position, or when it produces undefined. This means array defaults work the same way on strings, Sets, and generators.
const [first = '?', second = '?'] = 'x';
console.log(first, second); // 'x' '?'
function* oneValue() {
yield 'only';
}
const [g1 = 'none', g2 = 'none'] = oneValue();
console.log(g1, g2); // 'only' 'none'Common errors
- Expecting
nullto trigger the default. It never does. Add a??step ifnullshould mean missing. - Expecting
0,'', orfalseto be replaced. They are kept. This is usually what you want, and it is a reason to choose defaults over||. - Referring to a later target in a default. That throws a
ReferenceError. Reorder the pattern so dependencies come first. - Confusing
=with:in object patterns. In{ a = 1 }, the=sets a default. In{ a: b }, the:renames. You can combine them as{ a: b = 1 }, which the next chapter explains. - Putting a default on the source instead of the pattern.
const { x = 1 } = objhandles a missingx. It does not protect you whenobjitself isundefined. Parameter and nested destructuring chapters show the= {}fix.
Exercise
What does this log, and why? const [a = 1, b = a + 1, c = 9] = [undefined, null]; followed by console.log(a, b, c);
Show answer
It logs 1 null 9. Index 0 holds undefined, so a takes its default 1. Index 1 holds null, which is not undefined, so b is null and its default a + 1 is never evaluated. Index 2 is missing, so c takes its default 9.
Exercise
An API returns { pageSize: null, page: 0 }. Write code that produces pageSize of 20 when it is null or missing, and keeps page as 0 but makes it 1 when missing. Why can't a destructuring default alone handle pageSize?
Show answer
const { pageSize: rawSize, page = 1 } = data; const pageSize = rawSize ?? 20; gives pageSize 20 and page 0. A destructuring default fires only for undefined, and pageSize is null, so the default would be skipped. The ?? operator treats both null and undefined as missing and keeps 0, so it is the right tool for that property. page can use a plain default because 0 is present and should be kept.
Exercise
How many times is "called" logged? let calls = 0; const make = () => { console.log('called'); return ++calls; }; const [x = make(), y = make()] = [5]; const { z = make() } = { z: 0 };
Show answer
Once. x gets 5, so its default never runs. y is missing, so make() runs once and y becomes 1. z is 0, which is not undefined, so its default never runs. Defaults are evaluated lazily, only when the value read is undefined.