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 :
But with the new destructuring assignment you can instead do something like this :
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
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 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 :
Shorthand syntax if you have no constraints on the variable name:
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 :
Same thing, but now with objects :
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,