🧠 Difference Between Shallow Copy and Deep Copy in JavaScript
When we work with objects or arrays in JavaScript, we often need to copy them. But did you know there are two types of copies? 🧐
👉 Shallow Copy
👉 Deep Copy
Let’s understand both in simple words with a daily life example and easy code.
🍽️ Daily Life Example
Imagine you have a recipe book 📖. You want to give the same recipe to your friend.
Shallow Copy → You give a photocopy of the recipe page, but it still points to your original notes at the bottom. So if you change your notes, your friend sees the change too. 📝➡️👯♂️
Deep Copy → You write down the recipe fully with your notes and give it to your friend. Now, your friend has a completely separate copy. Changes in your book won’t affect your friend’s copy. 📝➡️📄✍️
🔄 What is Shallow Copy?
Shallow copy means copying only the top level of the object or array.
If there are nested objects/arrays inside, they are not fully copied - just the reference (link) is copied.
✅ Example:
let original = {
name: "John",
address: {
city: "Stockholm"
}
};
let shallowCopy = { ...original }; // or Object.assign({}, original)
shallowCopy.name = "Himanay"; // ✅ changes only in copy
shallowCopy.address.city = "Solna"; // ❌ also changes in original
console.log(original.address.city); // Solna
⚠️ Why?
Because address
is an object inside the main object. So only the reference is copied, not the actual data.
🌊 What is Deep Copy?
Deep copy means copying everything - including nested objects or arrays.
So the new object is totally separate from the original one.
✅ Example:
let original = {
name: "John",
address: {
city: "Stockholm"
}
};
// Deep Copy using JSON methods (best for simple objects)
let deepCopy = JSON.parse(JSON.stringify(original));
deepCopy.name = "Himanay"; // ✅ changes only in copy
deepCopy.address.city = "Solna"; // ✅ original stays the same
console.log(original.address.city); // Stockholm
🛑 Note:
JSON method won’t work if your object has functions or special types like Date
, undefined
, etc.
📌 Summary Table
Feature | Shallow Copy 📋 | Deep Copy 🧾 |
---|---|---|
Top-level copy | ✅ Yes | ✅ Yes |
Nested copy | ❌ No (just a reference) | ✅ Yes (fully copied) |
Independent? | ❌ Not fully | ✅ Fully independent |
Methods |
Object.assign() , spread |
JSON.parse(JSON.stringify()) or libraries like Lodash |
💡 When to Use?
👉 Use Shallow Copy when you only need to copy simple objects or don’t need full separation.
👉 Use Deep Copy when your object has nested data and you want a completely separate copy.
👨💻 Final Thought
Understanding the difference between shallow and deep copy helps you avoid unexpected bugs 🐞.
Always think: "Do I need a full copy or just a surface-level one?" before copying your data.
🧪 Try It Yourself
Play with the code on JSFiddle or your favorite code editor to see the difference.
Happy Coding! 💻🎉