CKTIS / JavaScript
Array destructuring binding
An array binding pattern initializes variables from values in iteration order. It can skip values, supply defaults, and collect the remaining values into a new array.
Version: ECMAScript 2024 and the current web platform; runtime support varies
Syntax
// Alternative declaration forms (use one):
{ const [first, , second = fallback, ...rest] = iterable; }
{ let [first, second] = iterable; }
var [first, second] = iterable;
function readPair([first, second]) {}
for (const [first, second] of pairs) {}Array destructuring binding declares and initializes names, as in const [first, second] = iterable. The pattern also works in let and var declarations, function parameters, declarations in for...of loops, and a catch parameter. By contrast, [first, second] = iterable is an assignment: it declares nothing and can write to existing writable targets such as obj.value, which is not a binding name.
The pattern takes values from a synchronous iterator, left to right, rather than reading numbered properties. That is why it also works with Set. An indexed object with a length but no iterator throws a TypeError, as does null or undefined as the entire input. In [, second], the empty slot skips the first value. In second = fallback, the default expression runs only if the value is undefined or the iterator has run out, not if the value is null.
...rest collects all remaining values into a new array without deep-copying them. The rest element must come last, with no trailing comma. Patterns can nest: [[first]] unpacks the first yielded value, which must itself be iterable. Without a rest element, the pattern does not pull extra values; if the iterator is not yet exhausted, JavaScript closes it, which can call its return() method.
Examples
{
const values = new Set([10, "skip", undefined, null, 30, 40]);
const [first, , second = 20, kept = 99, ...rest] = values;
console.log(JSON.stringify([first, second, kept, rest]));
}Result
[10,20,null,[30,40]]
`Set` yields values in insertion order. The empty slot skips `"skip"`, `undefined` triggers the default `20`, `null` stays unchanged, and `rest` contains `[30,40]`.
Related lessons
- JavaScript · Lesson 17 · Intermediate · Version: 3
- JavaScript · Lesson 20 · Intermediate · Version: 3
- JavaScript · Lesson 22 · Intermediate · Version: 3
- JavaScript · Lesson 35 · Intermediate · Version: 3