DEV Community

Discussion on: [JavaScript] 5 Interesting uses of JavaScript destructuring!

Collapse
 
darkwiiplayer profile image
𒎏Wii 🏳️‍⚧️

The usual way to swap 2 variables requires an additional temporary variable.

Yet destructuring requires a temporary array, which my intuition tells me, is harder (not impossible, mind you) to optimise and has to be garbage-collected.


let firstColor = 'white';
if (colors.length > 0) {
 firstColor = colors[0];
}
Enter fullscreen mode Exit fullscreen mode

There's a much nicer way to do this without destructuring:

let firstColor = colors[0] ?? "white"
Enter fullscreen mode Exit fullscreen mode

or using || on older javascript versions.


const [, ...fooNumbers] = numbers;
Enter fullscreen mode Exit fullscreen mode

Again, there's a much more readable version of this without destructuring:

const fooNumbers = numbers.slice(1)
Enter fullscreen mode Exit fullscreen mode

const { foo, ...small } = big;
Enter fullscreen mode Exit fullscreen mode

That's actually a really good example where destructuring is the most readable way of doing it. That being said, one could always just write a function to do a similar thing:

drop = (object, drop) => Object.fromEntries(Object.entries(object).filter(([key]) => drop.indexOf(key)))
Enter fullscreen mode Exit fullscreen mode

Is it pretty? no, not really. But at least it's possible :D


Personally, I really like using destructuring for function arguments. You might have already spotted it in my drop() example above: instead of indexing the array in the function body, I let the function declaration take care of that, and then just work with the variables I actually want in the body.

Getting many values out of a nested data structure is also really nice this way:

let {name: {first: firstname, last: lastname}, address: {street}} = user
Enter fullscreen mode Exit fullscreen mode
Collapse
 
yumatsushima07 profile image
Yuma-Tsushima

To be honest I do use || for destructuring also.

let firstColor = colors[0] ?? "white"
Enter fullscreen mode Exit fullscreen mode

or using || on older javascript versions.

You did make some good points here thanks :)

const fooNumbers = numbers.slice(1)
Enter fullscreen mode Exit fullscreen mode

I do also like the way you did this.

:) Thanks again