CKTIS / JavaScript
Destructuring default values
A destructuring default replaces only `undefined`. It preserves `null`, `false`, and `0`, and the fallback expression runs only when needed.
Version: ECMAScript 2024 and the current web platform; runtime support varies
Syntax
const { property: local = fallback } = source;
const [first = fallback] = iterable;
let target;
({ property: target = fallback } = source);
function configure({ volume = 10 } = {}) { return volume; }JavaScript destructuring defaults use = expression inside a pattern to supply a fallback for one property or element. JavaScript evaluates the expression only if the extracted value is undefined. Object patterns use ordinary property lookup, including inherited properties. Array patterns read from an iterator; if it runs out of values, a missing element is treated as undefined. Values such as null, false, 0, "", and NaN are preserved.
In const { volume: level = 10 } = source, volume is the property key and level is the new variable. To assign to an existing variable instead, use ({ volume: level = 10 } = source);. The parentheses keep the opening { from being read as the start of a block when the assignment is a standalone statement.
In function configure({ volume = 10 } = {}) { return volume; }, the outer = {} supplies an empty object when the argument is omitted or undefined. The inner = 10 applies only if reading volume yields undefined. Calling configure(null) throws a TypeError: the outer default does not replace null, and an object pattern cannot destructure it.
Examples
let calls = 0;
function fallback() {
calls += 1;
return 10;
}
const { volume: level = fallback(), muted = fallback(), label = "auto" } = {
volume: undefined,
muted: false,
label: null,
};
const [first = fallback(), second = fallback()] = [0];
console.log(JSON.stringify({ level, muted, label, first, second, calls }));Result
{"level":10,"muted":false,"label":null,"first":0,"second":10,"calls":2}`fallback()` is called only for `level` and `second`: `volume` is `undefined`, and the array iterator has no second element. The values `false`, `null`, and `0` are preserved, so `calls` is `2`.
Related lessons
- JavaScript · Lesson 2 · Intermediate · Version: 3