This is the second article of the EcmaScript 6 niceties serie. ES6 also known as ES2015 brought a truck-load of new features and structures into Javascript and renewed the language as we knew it. This serie will highlight a few of the ES6 niceties you might find useful in your next Javascript project.
Today’s article is about those funny dots; rest- and spread-operator.
When looking at ES6 code for the first time you’ll probably notice the usage of three dots … which you haven’t seen in any code written in Javascript’s earlier standards (<= ES5).
These three dots don’t necessarily do the same job, as there are two operators using that three-dot-syntax.
“The rest” can be assigned to a variable, using the rest-operator. Look at these rest-arguments:
Note that the rest operator must be a function’s last parameter!
The spread operator is sort of the opposite of the rest-operator: It takes an array of values, and turns it into ‘something else’ which uses comma-seperation. This might sound a little foggy, but these examples will clearify this:
The last example is called destructuring. In ES6 you can destructure ‘iterables’ (Array, Map, Set) and objects.
But you can’t destructure an object using the spread-operator. That could be so useful, especially working with React JS, where you find yourself often extracting values from props and state object literals.
But that is coming our way; Object Rest Spread proposal is in stage 4 in the ECMAScript approval process.
Using this Babel plugin enables you to use it now already.