Deep Copy vs Shallow Copy in JavaScript

ahtrahdis7

Sidhartha Mallick

Posted on January 5, 2022

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 using spread operator
b.addr.city = "Sambalpur"; // Shallow Copy

b.name = "A. Panda"; // Deep Copy

console.log(a.name, b.name); // separate references for name is created here
console.log(a.addr, b.addr); // a.addr and b.addr point to the same object reference
Enter fullscreen mode Exit fullscreen mode

Output:

Sambalpur Sambalpur
S. Sahu A. Panda
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

Output :

Behrampur Sambalpur
S. Sahu A. Panda
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

Output :

Sambalpur Sambalpur
A. Panda A. Panda
Enter fullscreen mode Exit fullscreen mode
💖 💪 🙅 🚩
ahtrahdis7
Sidhartha Mallick

Posted on January 5, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Deep Copy vs Shallow Copy in JavaScript
javascript Deep Copy vs Shallow Copy in JavaScript

January 5, 2022