How can I ignore certain returned values from array destructuring?

JavascriptArraysDestructuring

Javascript Problem Overview


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);

Javascript Solutions


Solution 1 - Javascript

> 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);

Solution 2 - Javascript

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);

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionKevBotView Question on Stackoverflow
Solution 1 - JavascriptKevBotView Answer on Stackoverflow
Solution 2 - Javascripthero in my lifeView Answer on Stackoverflow