DEV Community

Cover image for Deep Copy vs Shallow Copy in JavaScript
Sidhartha Mallick
Sidhartha Mallick

Posted on

3 2

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

AWS Q Developer image

Your AI Code Assistant

Automate your code reviews. Catch bugs before your coworkers. Fix security issues in your code. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Get started free in your IDE

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay