Our Blog

This is the second article of the EcmaScript 6 niceties serieES6 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.

Rest operator

“The rest” can be assigned to a variable, using the rest-operator. Look at these rest-arguments:

function replace(string, ...replacements) {
  // return another string;
}
function subtract(...numbersToSubtract) {
  return numbersToSubtract.reduce((sum, next) => sum - next);
}
subtract(10, 1, 2, 3); // 4

Note that the rest operator must be a function’s last parameter!

Spread operator

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:

// function calls
function combine(...numbers) {
  return subtract(...numbers) + add(...numbers);
}
combine(10,1,2,3); // 4+16=20

// assignments
const x = [1,2,3]; // 1,2,3
const y = [...x,4,5,6]; // 1,2,3,4,5,6
const z = [4,5,6,...x]; // 4,5,6,1,2,3
// assignments that converts Set and Map to an Array
let set = new Set([1, 2, 3, 3, 3, 4, 5]),
    array = [...set]; // [1,2,3,4,5];
let map = new Map([ ["name", "Sjoerd"], ["age", 40] ]),
    array = [...map]; // [ ["name", "Sjoerd"], ["age", 40] ]

// destructuring
const [a,b,...z] = y
a===1
b===2
z===[3,4,5,6]

Nearby future

The last example is called destructuring. In ES6 you can destructure ‘iterables’ (Array, Map, Set) and objects.

const { name, age } = { name: 'Sjoerd', age: 40, isDeveloper: true }

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.

const { x, y, ...z } = { x: 1, y: 2, a: 3, b: 4 }
x===1
y===2
z==={ a: 3, b: 4 }

In React practice

let props = {};
props.foo = x;
props.bar = y;
const component = <Component {...props} />;

const props = { foo: 'default' };
const component = <Component {...props} foo={'override'} />;
console.log(component.props.foo); // 'override'