Shallow and Deep Copy in JavaScript

Shallow and Deep Copy in JavaScript

Shallow Copy

Shallow copy is a bit-wise copy of an object. A new object is created that has exact same values as the original object. If any of the fields of the object are references to other objects, just the reference addresses are copied I.E, To cut the story short we can say that only the memory address is copied.

Deep Copy

A deep copy is like we copy all fields and make copies of dynamically allocated fields. A deep copy occurs when the object is copied along with the object it refers to .

Lets take an example

Shallow Copy: It makes a copy of the reference to X into Y. Think about it as a copy of X’s Address. So, the addresses of X and Y will be the same i.e. they will be pointing to the same memory location.

Deep copy: It makes a copy of all the members of X, allocates different memory location for Y and then assigns the copied members to Y to achieve deep copy. In this way, if X vanishes Y is still valid in the memory.

The correct term to use would be cloning, where you know that they both are totally the same, but yet different (i.e. stored as two different locations in the memory space).

consider this example

var employeeDetailsOriginal = {  name: 'Arush', age: 27, Profession: 'Software Engineer' };

Let’s say you want to create a duplicate of this, so that even if you change the original values, you can always return to the original.

var employeeDetailsDuplicate = employeeDetailsOriginal; //Shallow copy!

if we change the value

employeeDetailsDuplicate.name = 'NameChanged';

This statement will also change name from employeeDetailsOriginal, since we have a shallow copy, or a reference to var employeeDetailsOriginal. This means, you’re losing the original data as well.

But, creating a brand new variable by using the properties from the original employeeDetailsOriginal variable, you can create a deep copy.

var employeeDetailsDuplicate = { name: employeeDetailsOriginal.name, age: employeeDetailsOriginal.age, Profession: employeeDetailsOriginal.Profession}; //Deep copy!

Now if you change employeeDetailsDuplicate.name, it will only affect employeeDetailsDuplicate and not employeeDetailsOriginal

0_RGt-o4ovYiIt_9nS_.png