79

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);
KevBot
  • 17,900
  • 5
  • 50
  • 68
  • 2
    Related: [Destructuring array get second value?](https://stackoverflow.com/q/44559964/218196), [Object destructuring solution for long arrays?](https://stackoverflow.com/q/33397430/218196) – Felix Kling Oct 16 '17 at 16:43
  • Does this answer your question? [Destructuring array get second value?](https://stackoverflow.com/questions/44559964/destructuring-array-get-second-value) – RichieV Apr 22 '23 at 20:00

2 Answers2

140

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);
KevBot
  • 17,900
  • 5
  • 50
  • 68
  • Is it possible to ignore all items at the front and keep only a fixed bunch at the end? Something like `const [..., fourth_to_last, , penultimate, last] = my_list;` – BallpointBen Dec 06 '21 at 23:39
  • @BallpointBen, that's an interesting question. Unfortunately, rest elements must be the last element. A simple way to get the last items instead would be to reverse the array and vars: `const [last, penultimate, , fourth_to_last] = my_list.reverse();` – KevBot Dec 07 '21 at 03:33
1

Ignoring some returned values

You can use ',' ignore return values that you're not interested in:

const [, b, ...rest] = [1, 2, 3, 4, 5];

console.log(b);
console.log(rest);
PM 77-1
  • 12,933
  • 21
  • 68
  • 111