Spread and rest operator(...) in javascript

These ... in javascript were first introduced in ES2015(ES6) and it allows us to spread and rest multiple elements.

Both rest operator and spread operator refer to the same ... operator.

Why and how to use … in javascript and what it does?

There are two ways of using the ... in javascript:

Spread operator

The spread operator will spread all enumerable and own properties of one object.

Example 1:

const cars = ['Tesla', 'Mazda', 'BMW', {x:1}];
const all = [...cars];
console.log(all, cars[3] === all[3]);

As you might seen, from the example above you can make the following assumptions: - the spread operator will just enumerate the properties into another object

  • it makes a shallow copy of all the properties, so at cars[3] === all[3] we will get true as the object that is present in both arrays is the same. ( if we add cars[3].x = 2;  before printing to console we will get that x property changed throughout all arrays).

Example 2:

const person = { firstName: 'Daniel', lastName: 'Popa' };

console.log({...person, firstName: 'Viorel'}); // [object Object] { firstName: "Viorel", lastName: "Popa" }

Reading the example above you can get the following:

  • if duplicates elements are found, the last one wins, so in our example the value for firstName gets changed because after the object get’s spread a new duplicated key was present.

Rest operator

Before understanding the rest operator you must first read and understand javascript destructuring.

Even if the spread and rest parameters look the same they behave exact the opposite. If spread operator spread multiple elements, rest operator collects them.

Let’s see an example:

const arOfNumbers = [1, 2, 3];
const [ firstNumber, ...restOfTheNumbers ] = arOfNumbers;

We will have the following, firstNumberwill have the value 1 and restOfTheNumberswill be an array with only two elements inside of it [ 2, 3].  For the firstNumber we are using destructuring and because that we don’t want to select any other individual elements we are just gonna collect them in restOfTheNumbers using the rest operator (…) in front of our desired variable.

In our case the variable on what we used the rest operator was an array, but it dosen’t have to be an array, you can supply there any variable that is an enumerable, so const [firstCharacter, ...restOfCharacters] = 'danielpdev.io'; will also have the same output as in our example above.

You can read more about the rest operator here.

Get The Best Of All Posts Delivered To Your Inbox

Subscribe to our newsletter and stay updated.