Can I avoid declaring a useless variable when array destructuring when I am only interested in array values beyond index 0?
In the following, I want to avoid declaring a
, I am only interested in index 1 and beyond.
JavaScript
x
4
1
// How can I avoid declaring "a"?
2
const [a, b, rest] = [1, 2, 3, 4, 5];
3
4
console.log(a, b, rest);
Advertisement
Answer
Can I avoid declaring a useless variable when array destructuring when I am only interested in array values beyond index 0?
Yes, if you leave the first index of your assignment empty, nothing will be assigned. This behavior is explained here.
JavaScript
1
4
1
// The first value in array will not be assigned
2
const [, b, rest] = [1, 2, 3, 4, 5];
3
4
console.log(b, rest);
You can use as many commas as you like wherever you like, except after a rest element:
JavaScript
1
5
1
const [, , three] = [1, 2, 3, 4, 5];
2
console.log(three);
3
4
const [, two, , four] = [1, 2, 3, 4, 5];
5
console.log(two, four);
The following produces an error:
JavaScript
1
2
1
const [, rest,] = [1, 2, 3, 4, 5];
2
console.log(rest);