In this post we will learn what is spread operator in Javascript? How we can use it ? and Where we should use?
What is spread operator in Javascript ?
Spread Operator allows you to spread out the elements of an iterable object such as Array.
Syntax : [ ... Array ]
When to use spread operator ?
Suppose you have a array and you want to clone it.
let x = [1,2,3,4,5];
let y = x;
The above code is not cloning , x
sets a reference to y
, if the value of x
gets changed the the value of y
will also get changed.
There are many ways to can clone array in javascript
let x = [1,2,3,4,5];
let y = Object.assign([],x);
console.log(y);
//Output : [1,2,3,4,5]
In the above example we have use the Object constructor's assign method where we are creating a empty array and then assigning the elements form x.
Cloning using spread operator:
let x = [1,2,3,4,5];
let y = [...x]
console.log(y);
// Output:[1,2,3,4,5]
[...x]
it means spreading the elements of x
inside a empty array.
Merge two array into one using spread operator:
let x=[1,2,3];
let y=[4,5,6];
let z= [...x,...y];
console.log(z);
//Output : [ 1, 2, 3, 4, 5, 6 ]
...x = 1,2,3
...y = 4,5,6
[...x,...y] = [1,2,3,4,5,6]
Another way we can merge two arrays , by using concat() method.
let x=[1,2,3];
let y=[4,5,6];
let z= x.concat(...y);
console.log(z);
// Output : [ 1, 2, 3, 4, 5, 6 ]
Object Cloning using spread operator :
Object is also iterable so we can use spread operator in object . Below example let's see how we can clone a object using spread operator.
let site = {
name:"codelearningpoint",
cat : "technical"
};
let clonesite={...site};
console.log(clonesite);
//Output: { name: 'codelearningpoint', cat: 'technical' }
Merge two objects using spread operator :
We can use spread operator to merge two or more than two objects , But while merging the common property of objects will get overwrite.
In below example user1
and user2
both the objects are having name common property so in the Users clone object name property got added but only one time and name property took the latest value from the last object which is user2
const user1 = {
name: "user1",
location: "India",
};
const user2 = {
name: "user2",
location: "USA",
age:28
};
const Users = {...user1, ...user2};
console.log(Users)
//Output : { name: 'user2', location: 'USA', age: 28 }
I hope this article is helpful for you , i am very glad to help you thanks for reading