JavaScript Spread Operator

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

Its purpose is simple - to expand the said iterable variable, in place, where a list of values is expected.

Expanding Arrays

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`:


we get a slightly unexpected result:

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`:

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 ];
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; = 'red';

To create a copy:

let colour = { name: 'blue', score: 42};
let anotherColour = { ...colour }; = 'red';

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 };
Object { id: 25, isActive: true, name: "blue", score: 42 }

Passing Arguments

The spread operator can also be used to pass arguments to a function:

function sum(a, b, c) {
  return a + b + c;

const arr = [1, 2, 3];

console.log(sum(...arr)); // Output: 6

In this example, the spread operator is used to pass the elements of arr as arguments to the sum function - this allows the use of an array to call a function that expects individual arguments.

The spread operator is a powerful tool in JavaScript that can simplify one's code and make it more readable. It can be used to expand arrays, copy and combine objects, and pass arguments to functions. With the spread operator, one can write more concise and efficient code.