DEV Community

Shanthi's Dev Diary
Shanthi's Dev Diary

Posted on

Shallow Copy vs Deep Copy in JavaScript — Quick and Clear explanation

Copying objects in JavaScript looks easy… until the original object changes when you didn’t touch it.

Congratulations — you’ve encountered shallow copy chaos.

Let’s fix that in the simplest, funniest, most precise way possible.


🧍‍♂️ What Is a Shallow Copy?

A shallow copy only copies the top-level values.

Nested objects? Arrays?

JavaScript just hands you the same reference like a lazy coworker.

Example

const user = {
  name: "Shanthi",
  address: { city: "Chennai" }
};

const copy = { ...user };
copy.address.city = "Coimbatore";

console.log(user.address.city); 
// "Coimbatore" — betrayal detected 💔
Enter fullscreen mode Exit fullscreen mode

Why?

Because only the top-level value (name) was cloned.

The nested object (address) was shared, so modifying it changes the original.


🧠 What Is a Deep Copy?

A deep copy clones every level of the object.

  • No shared references
  • No accidental mutations
  • No “WHY DID THIS CHANGE??” debugging nightmares

Example

const user = {
  name: "Shanthi",
  address: { city: "Chennai" }
};

const deep = structuredClone(user);
deep.address.city = "Coimbatore";

console.log(user.address.city);
// "Chennai" — original untouched ✨
Enter fullscreen mode Exit fullscreen mode

🛠 Copying Methods

🔹 Shallow Copy Methods

  • { ...obj }
  • Object.assign({}, obj)
  • array.slice()
  • Array.from()

⚠️ Note: All shallow copy methods copy nested objects by reference, not by value.


🔹 Deep Copy Methods

  • structuredClone(obj)Best + modern
  • Custom recursive deep clone
  • JSON.parse(JSON.stringify(obj)) ⚠️ Breaks for:
    • Date
    • Functions
    • undefined
    • RegExp
    • Circular references

🎯 When Should You Use Which?

✔️ Use Shallow Copy when:

  • Only top-level values change
  • The object is simple
  • You just need a quick non-nested clone

✔️ Use Deep Copy when:

  • Your data is nested
  • You need immutability (React, Redux, etc.)
  • You want predictable, safe updates

🧘 TL;DR Table

Feature Shallow Copy Deep Copy
Copies nested values
Safe for complex data
Surprise bugs High Low
Best method Spread / Object.assign structuredClone()

🏁 Summary

Shallow and deep copying may sound similar, but they behave completely differently in JavaScript.

A shallow copy only duplicates the first level, leaving nested objects linked and ready to cause sneaky bugs.

A deep copy, however, clones every level, giving you safe, predictable, mutation-free data — especially important in React, Redux, and any place where immutability matters.

When in doubt:

  • Use shallow copy for simple, flat objects.
  • Use deep copy for anything nested or important.

Your future debugging sessions will thank you. 🚀

Top comments (0)