Javascript Spread operator


In this article i will demo the below uses of spread Operator in javascript 1.Merging Arrays 2. Copying Arrays 3.Passing Arrays as comma arguments. Traditionally we are using old ways like concat for merging, slice for copying and apply for passing array as arguments.

In this article i will demo the below uses of spread Operator in javascript
1.Merging Arrays
2. Copying Arrays
3.Passing Arrays as comma arguments.
Traditionally we are using old ways like concat for merging, slice for copying and apply for passing array as arguments.

The below example shows how we can merge two arrays into single array using spread operator.
Example for merging arrays using Spread operator:


var a =['1','2'];
var b= ['3','4'];
var c= [...a,...b];
console.log(c);

OUTPUT:
["1", "2", "3", "4"]


The below example shows how we can merge two arrays into single array using Concat function.
Example for merging arrays using Concat (old way):

var a =['1','2'];
var b= ['3','4'];
var c= a.concat(b)
console.log(c);

OUTPUT:
["1", "2", "3", "4"]


The below example shows how we can copy array using spread operator.
Example of copying arrays using Spread operator:

var a=["India", "Pakistan"];
var b=[...a]
console.log (b)

OUTPUT:
["India", "Pakistan"]


The below example shows how we can copy array using slice method.

Example of copying arrays using slice (old way):

var a=["India", "Pakistan"];
var b=a.slice()
console.log(b)

OUTPUT:
["India", "Pakistan"]


The below example shows how we can pass array as comma separated using spread operator


let a=["9", "2"];
var m= function(x, y)
{
if(x>y)
{
alert("x is Greatest");
}
else
{
alert("y is Greatest");
}
};
m(...a)

OUTPUT:
Alert Message with x is greatest

The below example shows how we can pass array as comma separated arguments using apply operator

let a=["9", "2"];
var m= function(x, y)
{
if(x>y)
{
alert("x is Greatest");
}
else
{
alert("y is Greatest");
}
};


m.apply(null, a)

OUTPUT:
Alert Message with x is greatest


There is one more use of spread operator (Destructuring). It is left to readers to explore this topic.


Comments

No responses found. Be the first to comment...


  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: