CKTIS / JavaScript
Object destructuring, default parameters, and property shorthand
Read options from one argument, distinguish the whole-parameter default from individual property defaults, and build the result with object property shorthand.
Version: ECMAScript 2024 and the current web platform; runtime support varies
Syntax
function configure({ limit: maxItems = 10, enabled = true } = {}) {
return { maxItems, enabled };
}Object destructuring/default parameter/shorthand syntax combines three features. In the configure signature, { limit: maxItems = 10, enabled = true } is a destructuring pattern. The function takes one positional argument, not named arguments. The pattern reads limit into the local binding maxItems and enabled into a binding of the same name.
The outer = {} creates a fresh empty object when the argument is omitted or explicitly undefined. The inner = 10 and = true apply independently, only when the corresponding property lookup yields undefined, including when no property is found. Property values of null, 0, false, and "" are preserved. By contrast, configure(null) throws a TypeError before the body runs. Without the outer = {}, omitting the argument would also throw a TypeError.
Default expressions are evaluated at call time and only as needed. They can use earlier initialized parameters, but not declarations inside the function body. Property lookup can follow the prototype chain or invoke a getter, so the pattern itself checks neither the value's type nor whether the property is an own property.
In return { maxItems, enabled }, the braces are an object literal that creates a new object, not a pattern. Property shorthand here has the same effect as { maxItems: maxItems, enabled: enabled }: the keys come from the local names, so the result has a maxItems key, not a limit key. This is ECMAScript syntax specified in the 2024 edition; check support in any older runtimes you target.
Examples
function configure({ limit: maxItems = 10, enabled = true } = {}) {
return { maxItems, enabled };
}
console.log(JSON.stringify(configure()));
console.log(JSON.stringify(configure(undefined)));
console.log(JSON.stringify(configure({ limit: 0, enabled: false })));
console.log(JSON.stringify(configure({ limit: undefined, enabled: null })));
try {
configure(null);
} catch (error) {
console.log(error.name);
}Result
{"maxItems":10,"enabled":true}
{"maxItems":10,"enabled":true}
{"maxItems":0,"enabled":false}
{"maxItems":10,"enabled":null}
TypeErrorThe first two calls produce the same result. The third preserves `0` and `false`, the fourth replaces only `undefined`, and the last logs `TypeError` because the whole argument is `null`.
Related lessons
- JavaScript · Lesson 42 · Advanced · Version: 4