Get "PHP 8 in a Nuthshell" (Soon includes PHP 8.4)
Amit Merchant

Amit Merchant

A blog on PHP, JavaScript, and more

Destructure a specific index of an array in JavaScript

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.

Like this article?

Buy me a coffee

👋 Hi there! I'm Amit. I write articles about all things web development. You can become a sponsor on my blog to help me continue my writing journey and get your brand in front of thousands of eyes.

Comments?