Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
110
rated 0 times [  112] [ 2]  / answers: 1 / hits: 21915  / 7 Years ago, mon, october 16, 2017, 12:00:00

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.





// How can I avoid declaring a?
const [a, b, ...rest] = [1, 2, 3, 4, 5];

console.log(a, b, rest);




More From » arrays

 Answers
126

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.





// The first value in array will not be assigned
const [, b, ...rest] = [1, 2, 3, 4, 5];

console.log(b, rest);





You can use as many commas as you like wherever you like, except after a rest element:





const [, , three] = [1, 2, 3, 4, 5];
console.log(three);

const [, two, , four] = [1, 2, 3, 4, 5];
console.log(two, four);





The following produces an error:





const [, ...rest,] = [1, 2, 3, 4, 5];
console.log(rest);




[#56214] Thursday, October 12, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
tomas

Total Points: 165
Total Questions: 111
Total Answers: 103

Location: Maldives
Member since Tue, Dec 21, 2021
3 Years ago
tomas questions
Thu, Jan 27, 22, 00:00, 2 Years ago
Mon, May 10, 21, 00:00, 3 Years ago
Tue, Jan 5, 21, 00:00, 3 Years ago
;