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];
console.log(newArr);
//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 = [...restaurant.mainMenu,'Gnoucci'];
console.log(newMenu);
Copying an Array:
Using the spread operator we can copy one array to another array as below:
const mainMenuCopy = [...restaurant.mainMenu];
Combine two array:
Using the spread operator we can combine two separate arrays into a new array as below:
const menu = [...restaurant.starterMenu,...mainMenuCopy];
Seprate Strings characters:
const str = 'Jignesh';
const letters = [...str,' ','s.']
console.log(letters);
//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){
console.log(num1+num2+num3);
}
sum(10,12,20);
//Output : 42
restaurant.orderPasta(...ingredients);
Using the spread operator we can write the above example as follows:
const sum = function(num1,num2,num3){
console.log(num1+num2+num3);
}
let params = [10,12,20];
sum(...params);
//Output : 42
const newRestaurant = { foundedIn: 1998, ...restaurant, founder: 'Guiseppe' };
console.log(newRestaurant);
const restaurantCopy = { ...restaurant };
restaurantCopy.name = 'Ristorante Roma';
console.log(restaurantCopy.name);
console.log(restaurant.name);
Conclusion:
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 Facebook, Twitter.