Skip to main content

Command Palette

Search for a command to run...

Shallow Copy vs Deep Copy in JavaScript

Updated
2 min readView as Markdown
Shallow Copy vs Deep Copy in JavaScript
M

I am passionate about learning, sharing knowledge, and growing through meaningful connections. My journey is all about embracing new challenges, evolving with every step, and collaborating with others to build something impactful.

When we work with objects in JavaScript, copying an object is not always as simple as it looks.

There are two common types of copying:

  • Shallow Copy

  • Deep Copy

Let's understand them with a simple example.

Shallow Copy

A shallow copy creates a new object, but nested objects are still shared.

const user1 = {
  name: "Mayur",
  address: {
    city: "Rajkot"
  }
};

const user2 = { ...user1 };

user2.address.city = "Ahmedabad";

console.log(user1.address.city);
// Ahmedabad

Why did user1 also change?

Because user1.address and user2.address are pointing to the same object.

console.log(user1.address === user2.address);
// true

The spread operator creates a shallow copy.


Deep Copy

A deep copy creates a completely independent copy, including nested objects.

We can use structuredClone():

const user1 = {
  name: "Mayur",
  address: {
    city: "Rajkot"
  }
};

const user2 = structuredClone(user1);

user2.address.city = "Ahmedabad";

console.log(user1.address.city);
// Rajkot

console.log(user2.address.city);
// Ahmedabad

Now changing user2 does not affect user1.

console.log(user1.address === user2.address);
// false

Easy Way to Remember

Think of it like this:

Shallow Copy
New object
Same nested object

Deep Copy
New object
New nested object

Common examples:

const shallow = { ...user };

const deep = structuredClone(user);

And remember:

const copy = user;

This is not a copy. Both variables point to the same object.

Conclusion

The main difference is simple:

Shallow copy → nested objects can be shared.

Deep copy → nested objects are also copied.

Once you understand object references, shallow and deep copying become much easier to understand.