Skip to main content
FREE Mock interview & resume review with Sumit. Free right now, no payment needed.Book a slot

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);
5
6const c = structuredClone(a);
7c.user.name = "Ravi";
8console.log(a.user.name);
VARIABLESHEAP (OBJECTS)a→ object A{ user }object Aname: "Sumit"user object
shared by two copies new copy just changed
Console
nothing printed yet

What 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 independent

Write 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

  1. Write deepEqual(a, b).

Keep learning