Ralph David Abernathy
Ralph David Abernathy

Reputation: 5518

How to use array destructuring on Javascript array with index of not 0?

I have the following variables:

$firstSection = $main.children[0];
$secondSection = $main.children[1];

To use array destructuring on the first variable, I can do this: [$firstSection] = $main.children;

However, how am I supposed to use array destructuring on the second variable? Thanks.

Upvotes: 1

Views: 1349

Answers (2)

cmprogram
cmprogram

Reputation: 1884

The values are accessed through a comma separated list, so:

 const [$firstSection, $secondSection] = $main.children; 
 console.log($secondSection); // The second value in the $main.children array

And if you actually don't need the first value in the array, for whatever reason - you can actually just use a comma to omit the first value.

const [, $secondSection] = $main.children;
console.log($secondSection); // The second value in the $main.children array

Upvotes: 1

CertainPerformance
CertainPerformance

Reputation: 371009

Just put the second item to destructure to the right of the first, in a comma-separated list. It looks very similar to when declaring an array with 2 items.

const [$firstSection, $secondSection] = $main.children;

Upvotes: 2

Related Questions