Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction  
2.
Shallow copy
3.
Deep copy
4.
How to solve the problem of shallow copying
4.1.
Spread syntax
4.2.
object.assign() method
4.3.
JSON.parse() method
5.
Difference between shallow copy and deep copy
6.
Frequently Asked Questions
7.
Conclusion
Last Updated: Mar 27, 2024
Easy

Explain the difference between shallow Copy and Deep Copy

Roadmap to SDE career at Amazon
Speaker
Anubhav Sinha
SDE-2 @
25 Jun, 2024 @ 01:30 PM

Introduction  

We all know that javascript is a high-level programming language. Like other languages, it also follows the concept of shallow copy and deep copy.

Normally, it looks like a standard copy, but it isn’t. There is a big difference between shallow copy and deep copy. So first, we will understand what a shallow copy and a deep copy is using some examples.

Shallow copy

A shallow copy is mainly a reference variable that stores the address of the object it is copied from. We are creating a new object with the same value as that of the original object. But if we change the values in this object, it will be affected in the original object also. So both objects share the same memory locations. Let's understand this with an example.

If we consider an object obj1 and store a name-value, say ‘Rajveer’ in it. Now we create another object name obj2 and copy obj1 into it. So in shallow copy, both the objects share the same memory allocation, and hence if we change the value of obj2, then the value of obj1 will also be changed.

It is making a copy of the reference of obj1 into obj2. It is pointing both obj1 and obj2 to the same memory locations. So when the value of one is changed, the other is changed automatically.

 

 

Now lets understand this using a code in javascript:

Implementation:

const develop1 = {
    name: 'Ranveer',
    age: 30
};


const develop2 = develop1;
console.log(develop1, 'develop1');
console.log(develop2, 'develop2');


console.log('modifying develop2');
develop2.age = 21;


console.log(develop1, 'develop1');
console.log(develop2, 'develop2');

 

Output:

So we can clearly see that when we changed develop2 , values of develop1 also changed.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Deep copy

Unlike shallow copy, deep copy copies all the fields and the memory allocated to it. Since it allocates different memory, it helps to create copied or cloned objects without worries of changing the old object. Let us understand this with examples.

If we consider an obj1 and store name and age in it say “Salman” ,“50”.Then we create a new obj2 and can copy obj1 into it. So in deep copying, when we change the value of obj2, there will be no changes in the value of obj1.

It is copying all values of obj1 and then assigning different memory locations to obj2. Hence if values of obj1 are changed or obj1 deletes, then there will be no changes in obj2.

 

Now let us understand this using a code in javascript.

Implementation:

const develop1 = {
    name: "Rajveer",
    age: 40
}


const develop2 = JSON.parse(JSON.stringify(develop1));
console.log("develop1 ",develop1);
console.log("develop2 ",develop2);


console.log("modifying develop2");
develop2.name = "Sushant";
develop2.age = 20;


console.log("develop1 ", develop1);
console.log("develop2 ", develop2);

 

Output:

We can clearly see that even when develop2 is changed , develop1 remains same.

How to solve the problem of shallow copying

There are three ways of copying an object in javascript.

  1. Spread syntax
  2. Using object.assign() method
  3. Using JSON.parse() and JSON.stringify() method

Spread syntax

Here spread method and object.assign() method performs a shallow copying while JSON.parse() and JSON.stringify() method perform a deep copying.

Example for spread syntax copying :

Implementation:

let person = {
    firstName: 'raj',
    lastName: 'arora',
      address: {
      city: 'delhi',
      state: 'india',
    }
};



let copiedPerson = {
    ...person
};


copiedPerson.firstName = 'Jane';
copiedPerson.address.city = 'agra'; 



console.log(person);
console.log(copiedPerson);

Output:

Here we can clearly see that firstName didn't change while the city changed. This is because the first name is a primitive value while address is reference value.Both of these are referenced to different object by addressed to similar address.

object.assign() method

Object.assign() method is similar to spread syntax. Both of these perform shallow copying. Example for object.assign() method copying.

Implementation:

let person = {
    firstName: 'raj',
    lastName: 'arora',
      address: {
      city: 'delhi',
      state: 'india',
    }
};



let copiedPerson = Object.assign({}, person);


copiedPerson.firstName = 'Jane';
copiedPerson.address.city = 'agra'; 



console.log(person);
console.log(copiedPerson);

 

Output:

JSON.parse() method

This method perform a deep copying so when copied object is changed there are no changes in original object.example of JSON.parse() method is:

Implementation:

let person = {
    firstName: 'raj',
    lastName: 'arora',
      address: {
      city: 'delhi',
      state: 'india',
    }
};



let copiedPerson = JSON.parse(JSON.stringify(person));


copiedPerson.firstName = 'Jane';
copiedPerson.address.city = 'agra'; 



console.log(person);
console.log(copiedPerson);

 

Output:

We can clearly see that even when copied person is changed, there are no changes in the person object.

You can also read about the memory hierarchy.

Difference between shallow copy and deep copy

Also see, Difference Between Compiler and Interpreter and Assembler

Frequently Asked Questions

  1. What is a reference object in javascript?
    In javascript, the object reference is information on how to find that object.it is the reference to that object to get to the memory.
     
  2. What is an object in javascript?
    Objects in javascript are also variable but they store many values together.
    To declare variables we use the let key while for objects we use the const key. for example:
    Const book = {name;”secret” , author:”Xyz” , price:”rs.500”};
     
  3. What is the use of object.create() method in javascript?
    Object.create() method is used to create a new object using the prototype of an existing object.for example:
    Const a=object.create(x);

Conclusion

In this blog, we have discussed about shallow copy and deep copy. We also learned the difference between shallow copy and deep copy. Also we learned a few coping mechanisms to overcome shallow copy using javascript language. We hope that this blog has helped you enhance your knowledge regarding program to convert pascal case string to snake case string and if you would like to learn more, check out our articles on javascript. Do upvote our blog to help other ninjas grow. Happy Coding!”

Previous article
Explain "this" keyword and Scope of this in Javascript Arrow Functions
Next article
Implement Custom Deep Clone Method
Live masterclass