When working with objects and arrays in JavaScript, developers often run into unexpected behavior because of how copies work. A major confusion is between shallow copy and deep copy.
🟠 What is a Shallow Copy?
Imagine you copy a room — it looks exactly the same: same walls, same furniture, same cupboard.
But here’s the catch — the cupboard inside is shared.
If you change something inside the cupboard in one room, it also changes in the other!
That’s what a shallow copy does.
const original = {
name: "Vimal",
skills: {
frontend: "React",
backend: "Node"
}
};
const shallow = { ...original };
shallow.skills.frontend = "Vue";
console.log(original.skills.frontend); // Output: "Vue" ❌
🟢 What is a Deep Copy?
Now imagine you not only copy the room but also build a completely new cupboard with its own items.
Now, if you change something inside this cupboard, it won’t affect the original.
That’s a deep copy in JavaScript.
const deep = JSON.parse(JSON.stringify(original));
deep.skills.frontend = "Angular";
console.log(original.skills.frontend); // Output: "React" ✅
Here, deep is fully independent — changes inside don’t affect the original.
Top comments (0)