loading...

Destructuring arrays as objects

mohananagavenkat profile image Mohana Naga Venkat Sayempu Updated on ・1 min read

Destructuring is one of the widely used feature of ES6. Since arrays are also objects in javascript we can destructure them by using their indices.

let fruits = ["Banana", "Orange", "Apple", "Mango", "Kiwi"];
let { 0:first } = fruits;
console.log(first); // Banana

In above example we are grabbing the first element of the array. Now we will go a little deep and try to grab the first, last and middle elements.

let fruits = ["Banana", "Orange", "Apple", "Mango", "Kiwi"];
let { length, 0:first, [Math.floor(length/2)]:middle, [length-1]: last } = fruits;
console.log(length, first, middle, last); // 5, Banana, Apple, Kiwi

Array have length property, so we grabbing that length and destructuring allows us to use that length right inside. Hence, we are using that length to calculate the middle position.

Happy coding πŸ˜ƒ.

Discussion

pic
Editor guide
 

See very little practical use for this but still interesting technique! If I used

let { length, [length-1]: last } = list;

I would just shock all my coworkers and would throw them off, instead of

let length = list.length;
let last = list[length-1];

This technique could really come in handy when need to grab two items out of a list at the same time though. That's a place I'd really consider using it, like with the

let { 0: a, 1: b } = list;
return a > b;

...or whatever. Well got me pondering of how to use it, very interesting. Thanks for sharing! :)

 

To be fair you can do that last example as

 let [a,b] = list
 return a > b

Which is way shorter. It would make sense perhaps for getting items from the end of a list, but as you say not very legible.

 

Oh yea forgot about that trick! The most interesting thing about this technique is to find where to use it.

 

I think you forgot to name middle

 

Yea, updated the post. Thanks for that πŸ˜ƒ

 

I can see using this on a sorted list for min, max, median, all the quantiles etc.

 

Yeah, that would be more realtime example πŸ˜ƒ