Sign in

Spread Operator in JavaScript

… what is it

The spread operator is commonly used to make a shallow copy of objects

let's take an example

Now if we want to copy the object obj_1 into obj_2 we do this

No doubt that the object obj_1 is copied in obj_2 but if we try to change any value either of obj_1 or obj_2 the changes will be reflected in both the objects or if we deleted any object both the objects will be deleted this is not preferred, So we use spread operator

Let’s take an example for the same

var obj_1 = {
name:"xyz"
}
var obj_2 = obj_1;
console.log(obj_1.name) // xyz
console.log(obj_2.name) // xyz
obj_2.name = "changed"console.log(obj_1.name) //changed
console.log(obj_2.name) //changed
/* delete made in one object is refelected in both */var obj_1 = {
name:"xyz"
}
var obj_2 = obj_1;
console.log(obj_1.name) //xyz
console.log(obj_2.name) //xyz
obj_2.name = "changed"
delete obj_2.name
console.log(obj_1.name) //undefined
console.log(obj_2.name) //undefined

Using spread operator

obj_2.name = "changed"console.log(obj_1.name) //xyz
console.log(obj_2.name) //changed
delete obj_2.nameconsole.log(obj_1.name) //xyz
console.log(obj_2.name) //undefined

Now to point what If I don't use the spread operator

var obj_2 = {obj_1};console.log(obj_2.name) // undefinedconsole.log(obj_2.obj_1.name) // xyz

Hope you got why you need to use the spread operator from the above instance