In essence, this is what destructuring does:
What used to take 3 lines now takes one. We can declare 3 variables and assign them to corresponding values of an object. The variable names and object properties names have to match.
If you have used the import statement in ES6, you might have run into things like:
This is one very common and useful way to use destructuring.
You can use ES6 default parameters in conjunction with destructuring
Here, we have assigned default values to
ceodoes not have a value setup in the initial object, the default value is used.
hqhas a value setup in the base object, the default value is not used.
In case using the object’s property names as variable names is not possible for you, it is possible to reassign them.
Here, we have reassigned the
google.ceo property to
If you want to assign values to existing variables, you need to use
It is possible to use destructuring with nested objects:
Just replicate the structure of the initial object. As you can see in the example above, you can change the variable name at the same time.
One creative use of destructuring would be declaring a for loop:
ceo values are extracted into new variables directly inside the loop declaration. Everybody will appreciate how clean and compact that looks like.
There are many other ways this can be used. Checkout MDN for more.
Thanks for reading !