Spread Operator makes life much easier for JS developers when it comes to doing basic operations on Arrays and Objects. Below are some examples of Spread Operator.
Spread Operator Syntax :
Array : […array]
Object : {…object}
Deep Copying Objects and Arrays
var original = { name: 'Rohit' };
var duplicate = { ...original };
console.log(duplicate);
// {name: "Rohit"}
var name = ['Rohit', 'Anant'];
var newName = [...name];
console.log(newName);
//["Rohit", "Anant"]
Concatenating Objects and Arrays
var fruits1 = ['Orange', 'Grapes'];
var fruits2 = ['Mango', 'Kiwi'];
var fruits = [...fruits1, ...fruits2];
console.log(fruits);
//["Orange", "Grapes", "Mango", "Kiwi"]
var data1 = { name: 'Orange' };
var data2 = { shape: 'sphere' };
var data = { ...data1, ...data2 };
console.log(data);
//{name: "Orange", shape: "sphere"}
Adding new values to Objects and Arrays
var fruits1 = ['Orange', 'Grapes'];
var fruits = [...fruits1, 'Mango', 'Kiwi'];
console.log(fruits);
//["Orange", "Grapes", "Mango", "Kiwi"]
var data1 = { name: 'Orange' };
var data = { ...data1, { shape: 'sphere' }};
console.log(data);
//{name: "Orange", shape: "sphere"}
Spreading Arrays
function showData(f1, f2, f3, f4) {
console.log(f1, f2, f3, f4);
}
var fruits = ["Mango", "Orange", "Kiwi", "Grapes"];
showData(...fruits);
// Orange Grapes Mango Kiwi