Destructuring arrays in JavaScript

ยท 2 min read
Destructuring arrays in JavaScript

When destructuring arrays in JavaScript we can easily start with the first elements of an array and then use the rest parameter to group the rest items till the very end:

const people = ['John', 'Jane', 'Jack', 'Mary'];

const [user1, user2, ...rest] = people;

console.log(user1, user2);

// John Jane

Unfortunately when we have large arrays with lots of children and we aim to reach pretty nested ones, this pattern is not that flexible. Not to forget that we cannot put the rest parameter upfront and this reduces our options a lot.

In the above example, if we need to pick the 3d and the 4th user we 'll have to do probably something like this:

const people = ['John', 'Jane', 'Jack', 'Mary'];

const [user1, user2, user3, user4] = people;

console.log(user3, user4);

// Jack Mary

Of course, variables user1 and user2 won't be used anywhere in the example above since we need only user3 and user4 but we cannot avoid picking them too.

An alternative approach might be to simplify this to:

const people = ['John', 'Jane', 'Jack', 'Mary'];

const [, , user3, user4] = people;

console.log(user3, user4);

// Jack Mary

Yikes. This is quite ugly and unreadable, right?

There is a cleaner way to pick these 2 users though by picking keys 2 and 3 and assigning these to two new variables accordingly:

const people = ['John', 'Jane', 'Jack', 'Mary'];

const { 2: user3, 3: user4 } = people;

console.log(user3, user4);

// Jack Mary

Array indexes start from 0 that is why we took keys 2 and 3 in our example.

Now that we saw this nifty trick let's remember how we can destructure objects:

const user = { firstName: 'John', age: 18 };

const { firstName } = user;

console.log(firstName);

// John

Or even assign firstName to another variable like name:

const user = { firstName: 'John', age: 18 };

const { firstName: name } = user;

console.log(name);

// John

Do you see the resemblance when destructuring specific keys for arrays and objects above? Cheers!!

Did you like this one?

I hope you really did...

Marios_thumb

Newsletter

Get notified about latest posts and updates once a week!!