JS - The three dots

Let the arguments flow

Posted by Sri Thotakura on June 23, 2016

The rest operator is used to get the arguments list passed to function on invocation.

function countArguments(...args) {
return args.length;
}
// get the number of arguments
countArguments('welcome', 'to', 'Earth'); // => 3

The spread operator is used for array construction and destructuring, and to fill function arguments from an array on invocation.

let cold = ['autumn', 'winter'];
let warm = ['spring', 'summer'];
// construct an array [...cold, ...warm] // => ['autumn', 'winter', 'spring', 'summer']
// destructure an array
let otherSeasons, autumn;
[autumn, ...otherSeasons] = cold;
otherSeasons // => ['winter']
// function arguments from an array
cold.push(...warm);
cold // => ['autumn', 'winter', 'spring', 'summer']