Destructure a specific index of an array in JavaScript

Amit Merchant · December 22, 2021 ·

One of the most important features of ES6 is destructing of arrays and objects.

So, using destructuring its possible to unpack values from arrays, or properties from objects, into distinct variables like so.

const [firstName, lastName, age] = ['Cherika', 'Merchant', 5];

firstName; // 'Cherika'
lastName; // 'Merchant'
age; // 5

The problem

Now, the problem with this approach is you have to have the same number of variables on the left-hand side of the assignment as the number of elements in the array on the right side.

And because of this, if you only want to retrieve say lastName, you would need to do something like this.

const [, lastName,] = ['Cherika', 'Merchant', 5];

lastName; // 'Merchant'

As you can tell, you would need to skip the indexes you don’t want on the left-hand side of the assignment.

Sure, this can get your job done but it looks ugly, and on top of that if the array contains more elements, you can imaging where this can lead you.

Choosing a specific index

To mitigate this, what you can do is, instead of using array destructuring, use the object destructing at the left-hand side and choose a specific index that you want from the array on the right-hand like so.

const { 1: lastName } = ['Cherika', 'Merchant', 5];

lastName; // 'Merchant'

As you can tell, this is already far more readable and clean. And since you are not skipping the indexes like in the previous approach, it’s more maintainable now.

👋 Hi there! I'm Amit. I write articles about all things web development. If you like what I write and want me to continue doing the same, I would like you buy me some coffees. I'd highly appreciate that. Cheers!

Comments?