ES6 Spread/Rest Operator

05.03.2020

ES6 has a handy feature called the Spread/Rest operator notated as .... The reason is has two names is because based on the use, it can do two different things.

Spread

For example, we can spread an array of values into a function parameters.

function myFunction(a, b, c) {
  console.log(a, b, c);
}

myFunction(...[1, 2, 3]); // outputs 1, 2, 3

We can also spread one array into another to improve array concatenation like so:

const a = [1, 2];
const b = [3, 4]'
const c = [...a, ...b];

console.log(c); // Results in [1, 2, 3, 4]

Rest

You can also use the operator to gather items into an array. A common usage of this is accepting extra arguments into a function

function myFunction(one, ...args) {
  console.log(args);
}

myFunction(1, 2, 3); // prints 1, [2, 3]

For more info, check the MDN docs