Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I ignore certain returned values from array destructuring?

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);
like image 858
KevBot Avatar asked Oct 16 '17 16:10

KevBot


People also ask

How do I set default value in Destructuring?

Default values in destructuring assignement only work if the variables either don't exist or their value is set to undefined . Any other value, including null , false and 0 , bypasses the default values in the destructuring statement. You can combine default values with renaming in the destructuring assignment.

How do you Destructure an array of objects?

To destructure an array in JavaScript, we use the square brackets [] to store the variable name which will be assigned to the name of the array storing the element.

Can you Destructure an array?

Nested Array DestructuringYou can also do nested destructuring with arrays. The corresponding item must be an array in order to use a nested destructuring array literal to assign items in it to local variables.

Why would you Destructure an array?

Destructuring can make working with an array return value more concise. In this example, f() returns the values [1, 2] as its output, which can be parsed in a single line with destructuring.


1 Answers

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);
like image 146
KevBot Avatar answered Sep 21 '22 17:09

KevBot