CKTIS / JavaScript
Destructuring function parameters
Put patterns directly in a function’s parameter list to read object properties or values from an iterable. Learn how whole-parameter defaults differ from defaults inside a pattern.
Version: ECMAScript 2024 and the current web platform; runtime support varies
Syntax
function readOptions({ label: name = "untitled" } = {}) { return name; }
function readFirst([count = 1] = []) { return count; }Using destructuring parameters means writing a binding pattern directly in a function’s parameter list. For an ordinary parameter, the pattern uses the value for one argument position and creates local bindings available in the function body. A rest parameter (...) can also use a binding pattern, but it destructures an array containing the remaining arguments. The arguments are still positional, not named.
The object pattern { label } reads a property by name and creates a local binding called label. With { label: name }, it reads the same property but binds its value to the local name name. The array pattern [count] takes the first value in iteration order, from an array or any other iterable.
Outer defaults = {} and = [] replace the whole argument before destructuring, but only when the argument is omitted or undefined. Inner defaults such as name = "untitled" and count = 1 apply only when the extracted value is undefined, for example when a property is missing or the iterator has no next value. null, 0, false, and "" do not trigger defaults.
Passing null as the whole argument to either pattern throws a TypeError before the function body runs. Without an outer default, omitting the argument or passing undefined also throws. An array pattern also throws a TypeError for a non-iterable value. Destructuring is not a substitute for input validation.
Examples
function describe({ label: name = "untitled" } = {}, [count = 1] = []) {
return `${name}: ${count}`;
}
console.log(describe());
console.log(describe({ label: "draft" }, [0]));
console.log(describe({ label: null }, []));Result
untitled: 1 draft: 0 null: 1
The first call uses both levels of defaults. The second preserves `0`. In the third, `label` is `null` and is not replaced, while the empty array triggers `count = 1`.
Related lessons
- JavaScript · Lesson 2 · Intermediate · Version: 3