Javascript Spread Operator

June 14, 2020

What is a spread operator?

The spread operator takes in an iterable (e.g an object) and expands it into individual elements.

It make copies of JS objects. This makes the code concise and enhances its readability.

I'll take you through how it is used in arrays, objects and functions.

Arrays

In the example below we have two arrays which we will merge into one new array.

const cars = ['Toyota', 'Hyundai', 'Mazda'];

const owner = ['Tom', 'Dick', 'Harry'];

The spread operator usually destructures what is on the right side of the value, in our case we will be destructuring the cars and the owner variables.

To spread you use three dots, which symbolise that you want to spread a particular variable.

const newArray = [...cars, ...owner];

console.log(newArray);

The above code should return the output below.

['Toyota', 'Hyundai', 'Mazda', 'Tom', 'Dick', 'Harry'];

That's it, you spread you're first array, Piece of cake right?

Side note.

just out of curiosity, have you ever wondered how developers used to combine two arrays before the spread operator was introduced to javascript in ES6

we will use the same example.

const newArray1 = cars.concat(owner);

It's still fine to use this, but as your code base grows, it would not be easy to read and understand it at a glance.

Brevity is a huge factor when it comes to software development, so thats why it is advisable to use the spread operator.

Lets see how it's done in objects/

Objects

This is where the spread operator gets interesting, it can be used in multiple scenarios.

I'll create two objects which i will use to demonstrate its use cases.


const carOne = {
    model:'Toyota',
    hp:450
    owner:'Tom'
}

const carTwo = {
    model:'Hyundai',
    hp:350
    owner:'Harry'
}

Accessing objects

This is how we would access an object without destructuring it.

Its pretty straight forward if your familiar with objects, if it's not, i suggets you take a look at objects and then come back to this.

console.log(carOne.model);

//This logs Toyota

The example below shows how to destruture it.

we use curly braces instead of square braces since its an object and not an array like the previous example.

const { model, hp } = carOne;

console.log(model);

//This logs Toyota

Both give the same output but one is easy to read compared to the other.

How about if you want to display the whole object?

instead of writing all the values of the object in the brackets we can use the spread operator.

const { ...allValues } = carOne;

console.log(allValues);

//This will return the whole object in carOne

Destructring inside functions.

The example below destrcutures the carTwo object inside a function and uses the object's properties

function displayCar({ model, hp, owner }) {
  console.log(`${owner}'s ${model}  has ${hp} horse power.`);
}

displayCar(carTwo);

//returns
//Harry's Hyundai  has 350 horse power.

That's how it is used in objects.