Spread Operator in JavaScript

By Saheb Sutradhar - Updated On 27-02-2024

Spread Operator in JavaScript

 

In this post, we will learn what is spread operator is in Javascript. How we can use it? and Where we should use it?

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 the spread operator?

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. 

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 an empty array.

 

Merge two arrays into one using the 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, 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 ]

 

Object Cloning using spread operator : 

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' }

 

Merge two objects using the spread operator : 

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 }

 

 

I hope this article is helpful for you, i am very glad to help you thanks for reading

 

 

codelearningpoint © 2024