ES6: Descructuring
8min read
With ES6 we get a convenient way of extracting multiple values from data stored in (possibly nested) objects and Arrays.
ES5
If we wanted to extract single values from an array in ES5 we would manually go through it by its index.
ES6
In ES6 we can simply sum up all variables in an array, give them appropriate names and reference it to the array we want to destruct.
Skip values
If we want to skip some values we just leave them out, but comma separate it that the length of both arrays will still match.
Rest Paramter + Destructuring
Another ES6 feature which comes really handy in combination with destructuring is the Rest Parameter. It is a sibling of the Spread Operator (they share the same syntax) and allows us to collect all the remaining elements into an array.
Destructure from Functions
We can destructure not only directly from an array but also from a function.
Default Parameters + Destructuring
By using Default Paramters we can assign default values in case our array has some undefined values. This could be for example the case when we retrieve the array via an API and cannot assure data reliability but need values to work with.
Swap values
A feature of destructuring that is not always easy to find real world applications for is swapping values. So in our case of the person object we can switch the values for the variables of firstname and lastname in one line.
Obviously this example doesn’t make a lot of sense because why would we switch firstname and lastname. I couldn’t come up with my own example that makes sense but I found a very good example on github: https://github.com/wesbos/es6-articles/blob/master/20%20-%20Swapping%20Variables%20with%20Destructuring.md
The example in a nutshell: We have a wrestling application in which the tag team partner always switch when they go into the ring. Without destructuring that problem would have been fixed with a temporare variable. Now we can use an easy one-liner.
Destructuring objects
Last but not least: Destructuring works also with objects.
Leave a Reply
Want to join the discussion?Feel free to contribute!