I'm trying to understand the difference between shallow copy and deep copy in JavaScript.
I know that if I copy an object using the spread operator or Object.assign(), only the first level is copied, but nested objects still reference the same memory location.
Example:
const user = {
name: "Alice",
address: { city: "Paris" }
};
const copy = { ...user };
copy.address.city = "London";
console.log(user.address.city); // "London" — changes in both!
So I understand this is a shallow copy.
However, I’ve seen many suggestions to use structuredClone(), JSON.parse(JSON.stringify(obj)), or libraries like lodash.cloneDeep.
My questions are:
What’s the actual difference between shallow and deep copy in memory terms?
Which method is the most reliable and performant for deep cloning in modern JavaScript?
Are there any limitations or edge cases (like Dates, Maps, Sets, or circular references) that I should be aware of?
I’d love a clear explanation and maybe a few short code examples showing when each method should be used.
Thanks!