A glance at Deep and shallow copy in JavaScript

Sharad Jaiswal
Sharad Jaiswal

Posted On: Sep 28, 2018

A glance at Deep and shallow copy in JavaScript

 

In object-oriented programming when we create a copy of an existing object, we call it as Object copying. The most common ways to copy an object is by using either a copy constructor or cloning. In Javascript, we have two ways to copy the object:- one is a shallow copy and the other is a Deep copy.

  • Shallow copy It is nothing but copying the reference pointer of the object which means the new object is also pointing towards the same memory reference of the old object and the memory usage will be hence lower. It will be accessing the same memory of the object which it is referring to.
  • Deep copy The object will produce a copy of itself, a new memory is allocated for the object and its contents. Hence, there will be a larger memory usage. Thus, the Deep clone is having the same set of the copy of the objects itself with a separate memory location.

A block diagram illustrating the Deep and Shallow concept

Let's clear it more with an example

Class A{
	int i;
	int j;
}
A obj= new A();// we created the object of class A
Obj.i=5;// setting the values for this object
Obj.j=6;

Now if we want to create one more object which has the same values as that of the original existing object .we can apply either shallow or deep copy concept.

Shallow copy

A obj1=obj; 
obj1.i // outputs 5
obj1.j// outputs 6

Here what is happening exactly is that we are not creating two objects, its one object only with two references. That is one object will be referring to two different references in the stack and both the references point to the same object. So, if somehow we change the value of obj1, it will reflect the values of obj because both are referring to the same object. So, we are creating only one object with two references in shallow copy.

Deep Copy

A obj= new A();                                      
Obj.i=5;                                                  
Obj.j=6;

A obj1=new A();
Obj1.i=obj.i;  // i=5
Obj1.j=obj.j;  // j=6

We create a new object. so,  we have two objects now and manually we copy the one-one value. And thus having two different objects referring to two different memory locations. Thus, if somehow the memory location of the original object gets deleted, the other objects memory locations will be intact. One disadvantage with Deep copy is that its time consuming, if we have to manually copy each and every value of the original object who has more than say for instance 3 values example 15 values.

So a new concept called cloning is introduced. In cloning, the object of the class can be cloned up. Here, we don't have to create a new object, it will automatically create the new object for you and it will have the same values.

It's basically a combination of two that is shallow copy and deep copy and you will get the cloned object.

A obj= new A();                                      
Obj.i=5;                                                  
Obj.j=6;
A.obj1=obj.clone();

When we clone, by default we are not allowed to copy the object, that is clone the object .we need to give permission and that is given with the help of a clonable interface.

Example Code for a better understanding of the deep copy and shallow copy

A shallow copy of the object can be done using object.assign() method in javascript.

let obj = {
  a: 1,
  b: 2,
};
let objCopy = Object.assign({}, obj);
console.log(objCopy);
// Result - { a: 1, b: 2 }

We have made a copy of obj. Let's see if immutability exists:

let obj = {
  a: 1,
  b: 2,
};
let objCopy = Object.assign({}, obj);
console.log(objCopy); // result - { a: 1, b: 2 }
objCopy.b = 80;
console.log(objCopy); // result - { a: 1, b: 80 }
console.log(obj); // result - { a: 1, b: 2 }

A Deep copy of the object can be done using JSON.parse(JSON.stringify(object));

let obj = { 
  a: 1,
  b: { 
    c: 2,
  },
}
let newObj = JSON.parse(JSON.stringify(obj));
obj.b.c = 20;
console.log(obj); // { a: 1, b: { c: 20 } }
console.log(newObj); // { a: 1, b: { c: 2 } } (New Object Intact!)

Another way to deep clone the object is :

function cloneObject(obj) {
    var clone = {};
    for(var i in obj) {
        if(obj[i] != null &&  typeof(obj[i])=="object")
            clone[i] = cloneObject(obj[i]);
        else
            clone[i] = obj[i];
    }
    return clone;
}

    Please Login or Register to leave a response.

    Related Articles

    JavaScript Tutorials

    JavaScript Vs Typescript

    Javascript Vs. Typescript: JavaScript and TypeScript are reputed and much debated over topics among web developers. Instead of discussing the pros and cons of these two languages. Here are few Differe..

    JavaScript Tutorials

    5 JavaScript Frameworks to learn in 2018

    JavaScript is the latest buzz in the web development industry that is extensively used by the developers to develop sophisticated web applications that will be having rich client-side interactions. Th..

    JavaScript Tutorials

    Comparison between JavaScript Top Frameworks react vs angular 2, vue js vs react, ember vs react

    Comparing top 3 Javascript Frameworks of 2018: Angular 5, React.js and Vue.js. JavaScript has a number of frameworks and libraries with a variety of functions and features, some specific and some with..

    Ask a Question