JavaScript deep copy and shallow copy

JavaScript deep copy and shallow copy

ยท

1 min read

Shallow Copy

Whenever we create a copy of an object, we are not only copying the values inside the object but also all the memory reference to that object. In that way the new object values are actually pointed towards the original object memory reference.

It always helps when there is an example.

const studentA = {
  name:"Tenzin",
  gender:"male"
}

const studentB =studentA;
studentB.name = "Mike"

console.log(studentB.name) // Mike
console.log(studentA.name) //Mike

Code block above demonstrates the working of shallow copy. Since we have created a shallow copy of object "studentA" into "studentB" and we try to change the value of "studentB" name, it also changes the name of "studentA."

Deep Copy

Unlike shallow copy, deep copy actually creates a new copy of the object with all the values and new memory reference to its values.

let's see the working of deep copy.

const studentA = {
  name:"Tenzin",
  gender:"male"
}

const studentB ={...studentA};
studentB.name = "Mike"

console.log(studentB.name) // Mike
console.log(studentA.name) //Tenzin

As shown in example when we create a new copy of object by Deep copying, the values of original object remains same. Keep in mind that there are many different ways of creating a Deep copy, here i have used "Spread operator" to achieve the same.

ย