Destructuring lets you unpack values from an array into separate variables in one line.
const colors = ["red", "green", "blue"];
const [first, second, third] = colors;
console.log(first, second, third); // → red green blue
Without it, you would write const first = colors[0]; and so on for each one.
Skipping items
Leave a gap with a comma.
const [a, , c] = [10, 20, 30];
console.log(a, c); // → 10 30
Default values
If the array is too short, the variable is undefined, unless you give a default.
const [x, y = 5, z = 9] = [1];
console.log(x, y, z); // → 1 5 9
Rest
Collect the remaining items with ....
const [head, ...tail] = [1, 2, 3, 4];
console.log(head); // → 1
console.log(tail); // → [2, 3, 4]
Swapping two variables
let a = "first";
let b = "second";
[a, b] = [b, a];
console.log(a, b); // → second first
In function parameters and returns
function minMax(numbers) {
return [Math.min(...numbers), Math.max(...numbers)];
}
const [min, max] = minMax([5, 2, 9]);
console.log(min, max); // → 2 9
This is exactly how useState works in React: const [count, setCount] = useState(0).
With loops and entries
const people = [["Maya", 25], ["Arjun", 28]];
for (const [name, age] of people) {
console.log(`${name} is ${age}`);
}
Destructuring from other iterables
It works on any iterable, such as strings, Sets and Maps:
const [firstLetter] = "hello";
console.log(firstLetter); // → h
Objects have their own version, see Object Destructuring.