By Saheb Sutradhar - Updated On 27-02-2024
In this post, we will learn what is spread operator is in Javascript. How we can use it? and Where we should use it?
Spread Operator allows you to spread out the elements of an iterable object such as Array.
Suppose you have an 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 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 used the Object constructor's assign method where we create an empty array and then assign the elements from x.
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 an empty array.
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, is by using the 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 ]
The object is also iterable so we can use the spread operator in an object. Below example let's see how we can clone an object using the spread operator.
let site = {
name:"codelearningpoint",
cat : "technical"
};
let clonesite={...site};
console.log(clonesite);
//Output: { name: 'codelearningpoint', cat: 'technical' }
We can use the spread operator to merge two or more two objects, But while merging the common property of objects will get overwritten.
In below example user1
and user2
both the objects have name property so in the Users clone object name property got added but only once time and the 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 }
Categories
Trending Posts
How to Disable the Submit Button in Formik...
How to Use Bootstrap 5 in Next.js...
What is Multer? How To Handling File Uploads in No...
How to Clear an Array in JavaScript...
How to Check if a Key Exists in a JavaScript Objec...
How to Open All Links in a New Tab Using JavaScrip...
JavaScript Array Filter...
What is the Next.js Image Component...
JavaScript Ternary Operator: A Concise Decision-Ma...
5 Ways to Remove Duplicate Object from Arrays in J...
codelearningpoint © 2024