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);
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.
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.
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.
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With