JavaScript Destructuring Arrays
Array destructuring pulls values out of an array by position. The first name takes the first value, and the second name takes the second value.
Take the first two values
The pattern takes values from the start of the array. The third value stays in the array, untouched.
const colors = ["red", "green", "blue"];
const [first, second] = colors;
console.log(first);
console.log(second);Skip a value with an empty slot
An empty slot takes no value. It only moves the pattern one position forward.
const scores = [10, 20, 30];
const [, middle, last] = scores;
console.log(middle);
console.log(last);Swap two values
Destructuring can assign as well as declare. The right side builds a new array, and the left side takes its values in the new order.
let a = 1;
let b = 2;
[a, b] = [b, a];
console.log(a);
console.log(b);Example
const days = ["Mon", "Tue", "Wed", "Thu"];
const [today, tomorrow] = days;
console.log(today);
console.log(tomorrow);
console.log(days.length);Key points
- Array destructuring: pulling values out of an array with a pattern in square brackets
- Position decides the match, not a name.
- Use an empty slot to skip a value in the array.
- The array keeps all its values after destructuring.
- A pattern can take fewer values than the array holds.
In this example, the pattern takes the first two days by position. The array still holds four values, so its length stays four.
Try it Yourself
Edit the code, then press Run.
Runs in your browser — the preview under the editor is the real result. Nothing is sent to a server. The code runner panel (right) does the same with more room.
Exercise
In const [first, , third] = [5, 6, 7];, what is third?