Shallow vs Deep Copy — JavaScript interview guide
21 / 23Interview CodingHigh priorityMedium 25 min
Shallow vs Deep Copy
A shallow copy copies only the top level; nested objects are still shared. A deep copy duplicates everything.
See it run
Press Play, or step with Next. Follow the arrows: anything that cannot be reached from a variable or root is free to go.
Shallow copy shares nested objects, deep copy does not
Step 1/7
copy.js
▶const a = { user: { name: "Sumit" } };2const b = { ...a };3b.user.name = "Amit";4console.log(a.user.name);56const c = structuredClone(a);7c.user.name = "Ravi";8console.log(a.user.name);
shared by two copies new copy just changed
Console
nothing printed yetWhat happens:Two objects are created: the outer object A and the nested user object. A only stores an ARROW (reference) to user.
Explained simply
Ways to copy
Spread and Object.assign are shallow. structuredClone is a built-in deep copy. JSON.parse(JSON.stringify(x)) loses dates, functions, undefined and Map/Set.
const a = { user: { name: "Sumit" } };
const b = { ...a };
b.user.name = "Amit";
a.user.name; // "Amit" — shared!
const c = structuredClone(a); // fully independentWrite deepClone yourself
Handle arrays, objects and circular references.
function deepClone(value, seen = new WeakMap()) {
if (value === null || typeof value !== "object") return value;
if (seen.has(value)) return seen.get(value);
const copy = Array.isArray(value) ? [] : {};
seen.set(value, copy);
for (const key of Object.keys(value)) copy[key] = deepClone(value[key], seen);
return copy;
}Remember this
- React state updates need new references at every changed level.
- structuredClone cannot copy functions or DOM nodes.
Interview questions
What is wrong with JSON.parse(JSON.stringify(obj))?
It drops functions and undefined, turns Dates into strings, fails on circular references and loses Map, Set, NaN and Infinity.
Practice
- Write deepEqual(a, b).