CKTIS / JavaScript
Array destructuring
Take values from an iterable in order, skip positions, provide defaults, and collect the remaining values in a new array.
Version: ECMAScript 2024 and the current web platform; runtime support varies
Syntax
const [first, , third = 20, ...rest] = iterable;
let value;
[value] = iterable;Array destructuring uses a [...] pattern to take values in iteration order. Unlike object destructuring ({...}), it does not select properties by name. The right-hand side can be an array or another iterable, such as a Set. Numeric keys and a length alone are not enough: a non-iterable source throws a TypeError.
In const [a, b] = iterable, the pattern declares new variables. The assignment [a, b] = iterable declares no bindings; it assigns values to a and b. If a target identifier cannot be resolved, the assignment throws a ReferenceError in strict mode. In a non-strict script, it can create a property on the global object instead. The empty slot in [a, , b] skips the second value yielded by the iterator.
If the iterator runs out, missing values are treated as undefined. The default expression in a = 10 is evaluated only when the value for a is undefined, not when it is null, 0, or false.
In [a, ...rest], the rest element ...rest gathers the remaining values into a new array, empty if none remain. It must come last and cannot have a trailing comma. This is JavaScript syntax specified in ECMAScript 2024, not a browser API; check support in your target runtime.
Examples
let [first = 10, , third = 20, ...rest] = [undefined, 99, null, 30, 40];
console.log(`${first} | ${third} | ${JSON.stringify(rest)}`);
[first] = new Set([5]);
console.log(first);Result
10 | null | [30,40] 5
`first` falls back to `10`, `99` is skipped, `third` stays `null`, and `rest` is `[30,40]`. The assignment then takes `5` from the `Set` and stores it in the existing `first` variable.
Related lessons
- JavaScript · Lesson 32 · Advanced · Version: 4
- JavaScript · Lesson 36 · Advanced · Version: 4
- JavaScript · Lesson 37 · Advanced · Version: 4
- JavaScript · Lesson 41 · Advanced · Version: 4
- JavaScript · Lesson 4 · Basic · Version: 4
- JavaScript · Lesson 2 · Intermediate · Version: 3