Deep copy VS Shallow copy

Deep copy VS Shallow copy

Deep copy and shallow copy are one of those concepts which are most frequently asked in interview . Even if you are not preparing for interview you must be aware of such concepts .So lets get started before any further delay .

Shallow copy

Knowingly or unknowingly you must have done shallow copy . So lets learn what is shallow copy ? Shallow copy is nothing but copy of an object whose property/ memory shares same reference .What it means is that when you try to change the values in copied object or the original object then the changes are reflected in both the objects .

Lets understand shallow copy with Example :

const Obj = {
name: "Bipin",
city: "Mumbai"
};

const copiedObj = Obj;

copiedObj.city = "Banglore";

console.log(Obj );
console.log(copiedObj);

Here the output will be :

{name: 'Bipin', city: 'Banglore'}

{name: 'Bipin', city: 'Banglore'}

In this case value of city got changed since both the objects are sharing same reference . But if we would have assigned new object instead of changing any perticular value then we would see that both of the objects will have different value as they dont share common reference .

Deep Copy

Unlike shallow copy , deep copy allocates new memory for the new object . So if the changes made in new object then those changes are not reflected in the original object . Deep copy makes both the objects indepented . In JavaScript deep copy can be created with the help of JSON.parse() and JSON.stringify() methods .

Now lets try to understand Deep Copy with the help of code :

let person = {
    firstName: 'Bipin',
    lastName: 'Yadav',
    address: {
        city: 'Mumbai',
        state: 'Maharashtra',
        country: 'India'
    }
};


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

copiedPerson.firstName = 'Ankit'; 

copiedPerson.address.city = 'Lucknow';

console.log(person);

console.log(copiedPerson)

Output :

address: {city: 'Mumbai', state: 'Maharashtra', country: 'India'} firstName: "Bipin" lastName: "Yadav"

address: {city: 'Lucknow', state: 'Maharashtra', country: 'India'} firstName: "Ankit" lastName: "Yadav"

In the above example , as a result of deep copy all the values in original object are different from copied object .

Thanks for your time .