Deep and Shallow Copy in Javascript


 

When it comes to creating an exact copy of an object in Javascript, we require creating a new object from an existing object. 

This can be achieved using various methods. We already have an article which can be referred on how to copy an object. Click here to visit.


But this article doesn't teaches you to create a copy of an object, this article is mainly focussed on the concepts of deep copy and shallow copy  in javascript and why we can't create copy an object by using the assignment operator.


Let's get started ..!!!


Almost everything in JavaScript is an object. In fact, only six things are not objects. They are — null , undefined , strings, numbers, boolean, and symbols. These are called primitive values or primitive types.

Arrays in Javascript are special types of objects. When you find the type of array by using typeof operator in javascript, you are going to get an object as output.


In Javascript, objects are reference values.


When you try to copy the object/ array using the = operator (assignment operator), it is only going to copy the reference to the original object/ array, and the value is not copied. 

Let's understand this with the help of an example. 



var arr = [1,2,3,4];
var copiedArr = arr;

copiedArr.push(5)

console.log(arr)
console.log(copiedArr)

Output

[1, 2, 3, 4, 5]
[1, 2, 3, 4, 5]


As you can see from the above example. We copied the array using the = operator (assignment operator) and then pushed one more value into the copied array.

Observe the output, the value got pushed into both the arrays. This happened because only the reference to the original object was copied not the value. (Shallow Copy)


Shallow Copy


A Shallow Copy in javascript means that certain (sub-)values are still connected to the original variable. In the above example, a shallow copy is created where only the reference is copied but the values are still linked. 

In Javascript, Composite Data Type like Objects, arrays are shallow copied.

Disadvantage of Shallow Copy

The Issue with Shallow copy is that, if the user makes changes to source object, it is also reflected in the Destination Object, since it is referenced by same memory address.


Deep Copy


A Deep copy in javascript means all the values of the new variable are copied and disconnected from the original variable.

When copying primitive data type in javascript like the number, string, booleans deep copy is created.


shallow copy and deep copy example

So, how can we create deep copy of an object. For this you can refer our next blog which explain this with help of multiple examples. Click here to visit.

Thanks for reading, please feel free to contact. 

Post a Comment

0 Comments