CKTIS / JavaScript
Array destructuring parameters
Use an array pattern to unpack one iterable argument in a function’s parameter list. Defaults for the argument and for individual values are separate.
Version: ECMAScript 2024 and the current web platform; runtime support varies
Syntax
function f([first = 1, , third = 3, ...rest] = []) { /* function body */ }Array destructuring parameters use an array binding pattern such as [first, third] to unpack one argument, not to declare two separate parameters. On each call, the pattern initializes local names from the argument in iteration order before the function body runs. An array works, as does another iterable such as a Set; a plain object with numeric keys and a length property is not enough.
In [first = 1, , third = 3, ...rest], the empty slot between commas skips the second value. ...rest collects the remaining values into a new array. It is a rest element inside the pattern, not a rest parameter that collects separate call arguments. It must come last, with no trailing comma.
The outer = [] supplies a replacement for the whole argument only when it is omitted or is undefined. The inner defaults = 1 and = 3 apply when the corresponding value is missing or is undefined. A null value inside the array stays null. Passing null or another non-iterable as the whole argument throws a TypeError before the body runs. Without = [], omitting the argument or passing undefined also throws a TypeError.
Examples
function describe([first = 1, , third = 3, ...rest] = []) {
return [first, third, rest];
}
console.log(JSON.stringify(describe()));
console.log(JSON.stringify(describe([undefined, 20, null, 40, 50])));
console.log(JSON.stringify(describe(new Set([10, 20, 30]))));
try {
describe(null);
} catch (error) {
console.log(error.name);
}Result
[1,3,[]] [1,null,[40,50]] [10,30,[]] TypeError
The first call uses both levels of defaults. In the second, `20` is skipped, `null` is preserved, and `rest` is `[40,50]`. The third shows that a `Set` also works. The last prints the error name rather than a runtime-specific message.
Related lessons
- JavaScript · Lesson 28 · Intermediate · Version: 3