ES6 Features 7: Destructuring
This week's ES6 Features post is going to be on some rather new syntactic sugar, called destructuring. Please be aware that neither Node.js or io.js support this syntax, and the only browser to have a decent level of support is Firefox.
Destructuring allows you to take an array's contents and assign it's values to multiple variables at once. Whereas before you would probably do this:
> var locations = [ "Paris", "New York" ];
undefined
> var first = locations[0], second = locations[1];
undefined
> first
'Paris'
> second
'New York'
You can now do this:
> var locations = [ "Paris", "New York" ];
undefined
> var [ first, second ] = locations;
undefined
> first
'Paris'
> second
'New York'
Destructuring also supports the rest operator (...), so you can assign the rest of the values in an array to a variable too:
> var fruits = [ "orange", "apple", "banana", "kiwi", "avocado" ];
undefined
> one
"orange"
> two
"apple"
> var [one,two,three,...rest] = fruits
undefined
> three
"banana"
> rest
["kiwi", "avocado"]
Destructuring in Ecmascript 7 can also be used on objects too, allowing you to set multiple variables equal to the value of a property in any object:
> var item = { "name": "compass", "quantity": 1, "value": 250 };
undefined
> var {name, quantity, value} = item;
undefined
> name
'compass'
> quantity
1
> value
250
In order for object destructuring to work, the variable names you are declaring must have the same name as the property of the object that you want to destructure.
Destructuring also works in a function context too! If you specify an object as the only parameter to a function, you can destructure it's contents into multiple variables. This looks like a good way to simplify complex functions that have a lot of arguments.
> function test({ x: x, y: y }) { return `(${x}, ${y})`; }
undefined
> test({ x: 250, y: 50 });
'(250, 50)'
That concludes this ES6: Features post on destructuring. To summarise, destructuring is a way simplify the assigning of multiple variables at once to the values in an array. The rest operator can be used to gather up the rest of the elements left in an array. Objects can be destructured too, by both variable assignments and the arguments of a function.
Destructuring isn't generally available yet though. Just before I end this post, here's a table of who supports it:
| Environment | Support? |
|---|---|
| Internet Explorer 11 | No |
| Microsoft Edge | No |
| Chrome 44 | No |
| Firefox 39 | Yes |
| Opera Beta 31 | No |
| io.js v2.3.1 | No |
| Node.js 0.12 | No |
| Babel | Yes |