DEV Community

Discussion on: Modern JavaScript, 10 things you should be using, starting today

Collapse
 
zirkelc profile image
Chris Cook

Great post with short and concise examples!
I'd like to add one more example for array destructuring. You can use the fact that arrays are objects and the array indices are object keys. That means with key 0 you get the fist element, but more importantly with a computed property key like [length-2] you can get an element in the middle of the array which is not possible with array destructuring and rest parameters:

const arr = [ 'one', 'two', 'three', 'four'];

const { 0: one, 1: two, length, [length-2]: three, 3: four } = arr;

console.log({ one, two, three, four })
Enter fullscreen mode Exit fullscreen mode

codesandbox.io/s/fancy-dust-24cwhr...

Collapse
 
samselfridge profile image
samselfridge

This seems like one of those things thats neat, but actually using it in practice will just result in some weird behavior thats difficult to track down...

Or that could just be my inner-old-man

Collapse
 
zirkelc profile image
Chris Cook

Extracting elements at the beginning of the array should be should be equivalent using array or object destructuring, because if the index does not exist the element is a going to be undefined in both cases: codesandbox.io/s/unruffled-babbage...

And if you want to extract only the last element (not possible using array destructuring), you have to use the length to calc the last index in the way as a direct array index access via brackets: codesandbox.io/s/elated-tdd-6nte4r...

Nevertheless, I wouldn't recommend object destructuring over array destructuring in all cases, but knowing about it shouldn't hurt either.