DEV Community

Discussion on: 4 Ways to Level-Up Your JS Destructuring and Spread Syntax

Collapse
 
thumbone profile image
Bernd Wechner

"I will add this tip is approaching the territory of too clever for its own good. You don't want to burden other developers with understanding some abstract functionality for what could have be a rudimentary, yet simple to understand piece of code." - I'm glad you ended with this. I was all into just that when I read:

const { fries, ...fruits } = food
Enter fullscreen mode Exit fullscreen mode

That blows my mind. Am I misunderstanding or are your really declaring fruits (implicitly as an array) and destructuring it on the LHS to receive food?

Like wow, I have to wonder if I want to know that ;-). And am tempted to read more on destructuring to gain some guru cred.

But then this:

const { length, [length-1]: lastItem } = bigDynamicArray
Enter fullscreen mode Exit fullscreen mode

What? Now arbitrarily the first entry is not a key in RHS (as fries was) but the length of RHS? By virtue of? What? This has me bamboozled and again I'm like: Do I really wanna know? That's some weird stuff going down there ...

Collapse
 
scottodea profile image
Scott O'Dea • Edited

Hey Bernd. I think you're confusing array style destructuring with object style destructuring. The order in which you destruct properties does not matter when using '{}' style destructuring.
Ex. const {a, b, c} = {c: 'foo', a: 'bar', b: 'baz'}
However, when destructuring using array syntax the order definitely matters as the properties pulled are ordered by index.
ex. const [firstElement, secondElement] = ['foo', 'bar']