Spread Operator in JavaScript

Spread Operator in JavaScript

In this tutorial, we will learn about spread operators in javascript.

So let's get started...

What is a spread Operator?

The spread operator was introduced to JavaScript in ES6 (ES2015),just like the rest parameters, which have the same syntax: three dots …

As the name says, the spread operator “spreads” the values in an iterable (arrays, strings) across zero or more arguments or elements.

Basically, We can use a spread operator to basically expand an array into all its elements.

Uses Examples:

Here we have listed some basic use cases of spread operator, like copying array, push to the array, combining two array, so let's take a look a look at it one by one.

Push one array to another array:

Using the spread operator we can push one array to another as below:

const arr1 = [7,8,9];

const newArr = [1,2,...arr1];
//Output : [1, 2, 7, 8, 9]

Push element to array:

Using the spread operator you can push one or more elements to the array as below:

const newMenu = [,'Gnoucci'];

Copying an Array:

Using the spread operator we can copy one array to another array as below:

const mainMenuCopy = [];

Combine two array:

 Using the spread operator we can combine two separate arrays into a new array as below:

const menu = [,...mainMenuCopy];

Seprate Strings characters:

const str = 'Jignesh';
const letters = [...str,' ','s.']
//Output : ["J", "i", "g", "n", "e", "s", "h", " ", "s."]

Using in the function call: 

We can use the spread operator in a function call. Suppose we have a function that takes a number of parameters and we have the parameters we want to pass it stored in an array. How can we call the function and pass the array of parameters?

Here’s how we would do that before ES6:

const sum = function(num1,num2,num3){

//Output : 42


 Using the spread operator we can write the above example as follows:

const sum = function(num1,num2,num3){

let params = [10,12,20];

//Output : 42
const newRestaurant = { foundedIn: 1998,, founder: 'Guiseppe' };
const restaurantCopy = { }; = 'Ristorante Roma';


 Thanks for reading.

Do let me know If you face any difficulties please feel free to comment below we love to help you. if you have any feedback suggestions then please inform us by commenting.

Don’t forget to share this tutorial with your friends on FacebookTwitter.

Subscribe to our Newsletter

Stay up to date! Get all the latest posts delivered straight to your inbox.

If You Appreciate What We Do Here On TutsCoder, You Should Consider:

If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.

Support Us

We are thankful for your never ending support.

Leave a Comment