Today we are here to talk about a new kind of operation that ES6 introduced, an operation that allows us to extract values from an array or an object in an easier way while using an array or object literal like syntax.

This feature is called destructuring assignment. Let’s start :

The old style

Back in ES5, if you wanted to extract values from an array you would have to do something like this :

Old Style initialization
Old Style initialization

But with the new destructuring assignment you can instead do something like this :

destructuring assignment
destructuring assignment

Super cool, right? So what’s happening here you might be wondering. Basically with this new syntax you can automatically assign the value of the corresponding indexes to a variable. You can also decide whether you assign the values to an existing variable or you can declare a new one by simply adding varlet or const in front of the assignment.

Destructuring assignment and rest parameters

You can also use this new special syntax with rest operators :

Destructuring assignment and rest parameters
Destructuring assignment and rest parameters

Destructuring assignment and objects

As mentioned earlier, we can also use this new feature with objects, the only big difference is that you have to specify the to be binded property. This whole process looks something like this :

Destructuring assignment and objects
Destructuring assignment and objects

Shorthand syntax if you have no constraints on the variable name:

Bonus cases

And if the examples that I have shown you weren’t enough to convince you to start using this amazing feature, then here I propose you other useful cases to harness the power of destructuring assignment :

Multiple return values :

Multiple return values
Multiple return values

Same thing, but now with objects :

Returning multiple objects
Returning multiple objects

Swapping values :

Swapping values
Swapping values

In the end

And that was it for this article, hope you enjoyed the examples and that from now one you will be able to write better code thanks to this amazing feature.

Stay tuned for more content,

Happy learning!

LEAVE A REPLY

Please enter your comment!
Please enter your name here