Spread Syntax vs Rest Parameter in ES2015 / ES6

Summary:

In javascript the ... is overloaded. It performs a different operations based on where the operator is used:

  1. When used in function arguments of a function declaration/expression it will convert the remaining arguments into an array. This variant is called the Rest parameters syntax.
  2. In other cases it will spread out the values of an iterable in places where zero or more arguments (function calls) or elements (array literals) are expected. This variant is called the Spread syntax.

Example:

Rest parameter syntax:

function rest(first, second, ...remainder) {
  console.log(remainder);
}

// 3, 4 ,5 are the remaining parameters and will be 
// merged together in to an array called remainder 
rest(1, 2, 3, 4, 5);

Spread syntax:

// example from MDN:

function sum(x, y, z) {
  return x + y + z;
}

const numbers = [1, 2, 3];

// the numbers array will be spread over the 
// x y z parameters in the sum function
console.log(sum(...numbers));


// the numbers array is spread out in the array literal
// before the elements 4 and 5 are added
const newNumbers = [...numbers, 4, 5];

console.log(newNumbers);

When using spread, you are expanding a single variable into more:

var abc = ['a', 'b', 'c'];
var def = ['d', 'e', 'f'];
var alpha = [ ...abc, ...def ];
console.log(alpha)// alpha == ['a', 'b', 'c', 'd', 'e', 'f'];

When using rest arguments, you are collapsing all remaining arguments of a function into one array:

function sum( first, ...others ) {
    for ( var i = 0; i < others.length; i++ )
        first += others[i];
    return first;
}
console.log(sum(1,2,3,4))// sum(1, 2, 3, 4) == 10;

ES6 has new feature three dots ...

Here is how we can use these dots:

  1. As Rest/Collector/Gather
var [c, ...m] = [1,2,3,4,5]; // m -> [2,3,4,5]

Here ...m is a collector, it collects the rest of the parameters. Internally when we write:

var [c, ...m] = [1,2,3,4,5]; JavaScript does following

var c = 1,
    m = [2, 3, 4, 5];
  1. As Spread
var params = [ "hello", true, 7 ];
var other = [ 1, 2, ...params ]; // other => [1,2,"hello", true, 7]

Here, ...params spreads so as to adding all of its elements to other

Internally JavaScript does following

var other = [1, 2].concat(params);

Hope this helps.