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 }
Trending Posts
Create Input Floating Label in CSS and HTML...
CSS Card Hover Effects: Make Your Website Stand Ou...
Create a Rotate Image Gallery with HTML and CSS...
CSS Hover Effect | Web Development...
How to create MongoDB Free cloud Database - Atlas ...
Learn how to create CSS Button RGB Animation...
Create Responsive Sidebar with React JS and tailwi...
Build a JavaScript Carousel Slider With Example...
How to Disable the Submit Button in Formik...
How to Use Bootstrap 5 in Next.js...
codelearningpoint © 2024