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 😃.
Top comments (7)
See very little practical use for this but still interesting technique! If I used
I would just shock all my coworkers and would throw them off, instead of
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
...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
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 😃