ES6 version of JavaScript introduced a lot of great improvements, and amongst them was the spread operator. It's syntax is slighly unusual: three dots followed by a name of an iterable variable.

Its purpose is simple - to expand the said iterable varable, in place, where a list of values is expected. Let's see an example - given the 2 arrays of colours below:

let colours = ['red', 'blue', 'green'];
let pastels = ['pink', 'lavender', 'peach'];

When we try to append `pastels` to `colours` using `push`:

colours.push(pastels);

we get a slighly unexpected result:

console.log(colours); 
// Array(4) [ "red", "blue", "green", (3) […] ]

The `pastels` array is added as the fourth element - that's because `push` simply appends the parameter given.

Spread operator to the rescue

To get the expected behaviour, we'll have to use the spread operator when passing `pastels` to `push`:

colours.push(...pastels);
console.log(colours); 
// Array(6) [ "red", "blue", "green", "pink", "lavender", "peach" ]

In our case, the spread operator is equivalent to pushing individual elements:

colours.push(pastels[0], pastels[1], pastels[2]);

What if we want to create a new variable that holds both arrays? That's simple enough:

let colours = ['red', 'blue', 'green'];
let pastels = ['pink', 'lavender', 'peach'];
let allColours = [ ...colours, ...pastels ];
console.log(colours); 
// Array(6) [ "red", "blue", "green", "pink", "lavender", "peach" ]

Object copy

Another common place where the spread operator can be useful is for when making copies of objects.

Simply assigning an object value to another variable will reference to the same object:

let colour = { name: 'blue', score: 42};
let anotherColour = colour;
anotherColour.name = 'red';
console.log(colour.name); 
// red

To create a copy:

let colour = { name: 'blue', score: 42};
let anotherColour = { ...colour };
anotherColour.name = 'red';
console.log(colour.name); 
// blue

Combine objects

Just like with arrays, the spread operators can be used to "combine" the properties of 2 objects:

let colour = { name: 'blue', score: 42};
let apiColour = { id: 25, isActive: true};
let fullColour = { ...apiColour, ...colour };
console.log(fullColour); 
// Object { id: 25, isActive: true, name: "blue", score: 42 }

Next Steps