JavaScript
Destructure object properties with defaults
Destructuring can name local variables and supply defaults for undefined properties. Use it to make a small set of expected options visible at the start of a function.
Worked example
Node.js example · save as example.mjs and run node example.mjs
function describe({size = 10, theme = "system"} = {}) {
return `${size}:${theme}`;
}
console.log(describe());
console.log(describe({size: 0, theme: null}));How it works
The empty-object parameter default handles a missing argument. The property defaults handle missing or explicitly undefined fields inside that object. Zero is preserved, and null is also preserved because destructuring defaults do not use nullish semantics.
Limits and mistakes
Passing null as the whole argument still fails because there is no object to destructure. If callers may send null, validate or normalize it before destructuring. Defaults are not a substitute for checking valid ranges or types.
Check the result
Expect 10:system and 0:null. Test an omitted argument, an empty object, undefined fields, and an explicitly null argument to establish your function’s contract.
Sources
Reference documentation for the behavior used in this guide: