I met a great destructuring assignment through my brother Weslley Araujo, and I need to confess that I really liked it. It is nothing more than an expression that allows us to get data from objects or arrays in a much simpler way.
For we get a property of an object, we could do something like that:
With the new guy, we could do something like that:
With arrays
If we wanted to take the first item of an array
, we could do something like:
With the fella destructuring, we could do:
It is still possible, play a bit more:
Using when importing files
A very cool thing to use destructuring assignment is when we need to import things to our files. Imagine we have a generic file, as a helpers, something like that:
Nice! In other file, let’s suppose that we need only these two functions, and not the entire file. So, let’s go:
Applying to forEach
We could use to in the famous forEach
. So, if we have a data like that:
With this data, normally we could do something like that:
With the double of arrow-functions and destructuring, we got some powers:
Creating objects
We could create objects in this way:
But there is a new way much more fun. ◕‿◕
Here you can find an JS Bin with the examples.