Deep Copy vs Shallow Copy in JavaScript

Deep Copy vs Shallow Copy in JavaScript

Shallow Copy

A new object is created that has an exact copy of the values in the original object. If the original object points to another object, a separate copy of that object is not created, rather a reference to that object is passed.

const a = {
    name: 'S. Sahu',
    addr:  {
        city: 'Behrampur',
    }
}
const b = {...a}; // shallow copy occurs here
b.addr.city = "Sambalpur"; // Shallow Copy
b.name = "A. Panda"; // Deep Copy
// separate references for name is created here
console.log(a.name, b.name); 
// a.addr and b.addr point to the same object reference
console.log(a.addr, b.addr);

Output :

Sambalpur Sambalpur
S. Sahu A. Panda

Deep Copy

A deep copy copies all fields, and makes copies of dynamically allocated memory pointed to by the fields. A deep copy occurs when an object is copied along with the objects to which it refers.

const a = {
    name: 'S. Sahu',
    addr:  {
        city: 'Behrampur',
    }
}

const b = {
    name: a.name,
    addr: {
        city: a.city
    }
};

b.addr.city = "Sambalpur";
b.name = "A. Panda";

console.log(a.addr.city, b.addr.city);
console.log(a.name, b.name)

Output :

Behrampur Sambalpur
S. Sahu A. Panda

Create Reference

A reference of the original object is created. Any changes made in the new object is reflected in the original object.

const a = {
    name: 'S. Sahu',
    addr:  {
        city: 'Behrampur',
    }
}

const b = a;

b.addr.city = "Sambalpur";
b.name = "A. Panda";

console.log(a.addr.city, b.addr.city);
console.log(a.name, b.name)

Output :

Sambalpur Sambalpur
A. Panda A. Panda

! Happy Coding !

Did you find this article valuable?

Support De-mystify Tech by becoming a sponsor. Any amount is appreciated!