CKTIS / JavaScript
Array destructuring parameter
Unpack values from one iterable argument directly in a function signature, and distinguish an element default from a default for the entire parameter.
Version: ECMAScript 2024 and the current web platform; runtime support varies
Syntax
function describe([first = "default", , ...rest] = []) {
return JSON.stringify([first, rest]);
}An Array destructuring parameter uses an array binding pattern such as [first, second] to unpack one argument before the function body runs. The names first and second are available in the body. The pattern reads values in iteration order, so the argument can be an array or another iterable such as a Set. A plain object with numeric indexes and a length but no iterator causes a TypeError.
In [first = "default", , ...rest] = [], the outer = [] substitutes an empty array when the argument is omitted or is undefined. The inner = "default" applies when the iterator yields no first value or yields undefined first. Passing null as the argument causes a TypeError before the body runs; passing [null] binds first to null.
The empty slot between commas skips the second value. The rest element ...rest collects all remaining values into a new array; it must come last in the pattern, with no trailing comma. Unlike the rest parameter in function f(...args) {}, it collects values from one argument, not the remaining arguments of the call.
Examples
function describe([first = "default", , ...rest] = []) {
return JSON.stringify([first, rest]);
}
console.log(describe());
console.log(describe(["A", "skip", "B", "C"]));
console.log(describe(new Set([undefined, "skip", "Z"])));
console.log(describe([null]));Result
["default",[]] ["A",["B","C"]] ["default",["Z"]] [null,[]]
The first call uses both defaults. The second skips `"skip"`; the third reads from a `Set` and uses the inner default for `undefined`. The fourth preserves `null`.
Related lessons
- JavaScript · Lesson 7 · Advanced · Version: 4