Skip to content
jshacks.dev
Fundamentals

JavaScript Interview Question Shallow vs Deep Copy

How to answer shallow versus deep copy: a shallow copy shares nested objects, a deep copy duplicates them. See spread, structuredClone and JSON pitfalls.

8 min read
Summarize in AI
Flat illustration of two options weighed side by side, with the JavaScript, Node.js, Vite and npm logos.

"What is the difference between a shallow and a deep copy" is a question about references, and the interviewer wants to see that you understand what happens when you copy an object that contains other objects. The answer has four parts: assignment does not copy at all, a shallow copy duplicates the top level and shares everything nested, a deep copy duplicates every level, and there are several ways to make a deep copy, each with limits. Candidates who know only JSON.parse(JSON.stringify(x)) lose points when asked what it breaks, and candidates who know structuredClone gain them. This post gives the answer in thirty seconds, then each kind of copy with exact output, the limits of JSON and structuredClone, a hand-written clone, and the wrong answers to avoid. The examples run on Node.js 24.

The answer in thirty seconds

Objects and arrays are held by reference. Assigning one to another variable makes a second name for the same object, with no copy at all. A shallow copy creates a new top-level object and copies the values of its properties, and when a value is itself an object, only the reference is copied, so the original and the copy share it. A deep copy creates new objects at every level, so the two share nothing and changing one cannot affect the other.

JavaScript
const original = { name: "Ada", skills: ["math"], address: { city: "London" } };

const alias = original;
const shallow = { ...original };
const deep = structuredClone(original);

original.name = "Grace";
original.skills.push("code");
original.address.city = "New York";

console.log(alias.name, alias.skills, alias.address.city);
console.log(shallow.name, shallow.skills, shallow.address.city);
console.log(deep.name, deep.skills, deep.address.city);
Text
Grace [ 'math', 'code' ] New York
Ada [ 'math', 'code' ] New York
Ada [ 'math' ] London

The alias saw every change, because it is the same object. The shallow copy kept its own name, since a string was copied by value, and shared skills and address, which were changed through the original. The deep copy kept everything as it was. This one snippet, with the three results, is the answer, and the rest is detail.

Ways to make a shallow copy

Several common operations are shallow, and the interviewer may ask you to list them.

JavaScript
const source = { id: 1, tags: ["a"] };
const list = [{ n: 1 }, { n: 2 }];

const copies = [
  { ...source },
  Object.assign({}, source),
  Object.fromEntries(Object.entries(source)),
];

console.log(copies.every((copy) => copy !== source && copy.tags === source.tags));

const arrayCopies = [[...list], list.slice(), Array.from(list), list.concat(), list.map((x) => x)];

console.log(arrayCopies.every((copy) => copy !== list && copy[0] === list[0]));
Text
true
true

Object spread, Object.assign, and rebuilding from entries all make a new object that shares the nested tags array. For arrays, spread, slice(), Array.from(), concat() and map() with an identity function all make a new array whose elements are the same objects. Each copy fails the identity test at the top level and passes it for the nested value. When the data holds only primitives, such as numbers and strings, a shallow copy is a full copy, which is why it is the right tool for flat data.

Why a shallow copy bites

The bug appears when you copy to avoid changing the original, then change a nested value.

JavaScript
function addTag(item, tag) {
  const copy = { ...item };
  copy.tags.push(tag);
  return copy;
}

const item = { id: 1, tags: ["a"] };
const updated = addTag(item, "b");

console.log(item.tags, updated.tags, item.tags === updated.tags);
Text
[ 'a', 'b' ] [ 'a', 'b' ] true

The function copied the item to leave the original alone and then mutated the shared array, so the original changed as well. The fix is to copy the level you change: { ...item, tags: [...item.tags, tag] }. For deep structures, copying each changed level by hand is the immutable update pattern, and it avoids the cost of cloning everything.

structuredClone

structuredClone() is the built-in deep copy, available in Node.js 17 and later and in current browsers.

JavaScript
const data = {
  when: new Date(0),
  missing: undefined,
  nan: NaN,
  pattern: /a+/g,
  map: new Map([["k", { deep: true }]]),
  set: new Set([1, 2]),
  nested: { list: [1, [2, 3]] },
};

const clone = structuredClone(data);

console.log(clone.when instanceof Date, clone.when.getTime());
console.log("missing" in clone, clone.nan);
console.log(clone.pattern.source, clone.pattern.flags);
console.log(clone.map.get("k"), clone.map.get("k") === data.map.get("k"));
console.log(clone.set.has(2), clone.nested.list[1] === data.nested.list[1]);
Text
true 0
true NaN
a+ g
{ deep: true } false
true false

It preserves dates, regular expressions, maps, sets, undefined values and NaN, and it duplicates nested objects at every level, as the identity checks that print false show. It also handles cycles, which the JSON approach cannot.

JavaScript
const node = { name: "root" };
node.self = node;

const copy = structuredClone(node);

console.log(copy.self === copy, copy === node);

try {
  JSON.stringify(node);
} catch (e) {
  console.log(e.name, "-", e.message.split("\n")[0]);
}
Text
true false
TypeError - Converting circular structure to JSON

The clone keeps the cycle, pointing at itself and not at the original. The JSON method throws.

The limits of structuredClone

It copies data, not behavior.

JavaScript
class Point {
  constructor(x) {
    this.x = x;
  }
  get double() {
    return this.x * 2;
  }
}

const point = new Point(2);
const pointCopy = structuredClone(point);

console.log(point.double, pointCopy.double);
console.log(pointCopy instanceof Point, Object.getPrototypeOf(pointCopy) === Object.prototype);

for (const value of [{ fn() {} }, { sym: Symbol("s") }, new WeakMap()]) {
  try {
    structuredClone(value);
  } catch (e) {
    console.log(e.name);
  }
}
Text
4 undefined
false true
DataCloneError
DataCloneError
DataCloneError

A class instance comes back as a plain object: the prototype is lost, so the getter and every method are gone. Functions, symbols and weak collections cannot be cloned at all, and throw a DataCloneError, covered in DOMException. If your data has class instances, a deep copy needs a custom approach, such as a clone() method on the class.

The JSON trick and what it breaks

JSON.parse(JSON.stringify(value)) was the standard deep copy before structuredClone, and it is the answer many candidates know.

JavaScript
const source = {
  when: new Date(0),
  gone: undefined,
  fn() {},
  nan: NaN,
  inf: Infinity,
  map: new Map([[1, 2]]),
  set: new Set([1]),
  regex: /a/g,
  nested: { ok: true },
};

const viaJson = JSON.parse(JSON.stringify(source));

console.log(viaJson);
console.log(typeof viaJson.when);
Text
{
  when: '1970-01-01T00:00:00.000Z',
  nan: null,
  inf: null,
  map: {},
  set: {},
  regex: {},
  nested: { ok: true }
}
string

The date became a string, undefined and the function vanished, NaN and Infinity became null, and the map, set and regular expression became empty objects. It also throws for BigInt values and for cycles. It is acceptable for plain data made of objects, arrays, strings, numbers, booleans and null, and wrong for anything else. A date that turns into a string breaks the next line that calls .getTime() on it.

A hand-written deep clone

Interviewers often ask for the recursive version.

JavaScript
function deepClone(value) {
  if (value === null || typeof value !== "object") return value;
  if (value instanceof Date) return new Date(value.getTime());
  if (Array.isArray(value)) return value.map(deepClone);

  const result = {};
  for (const key of Object.keys(value)) {
    result[key] = deepClone(value[key]);
  }
  return result;
}

const tree = { a: [1, { b: 2 }], d: new Date(0), n: null };
const treeCopy = deepClone(tree);

console.log(treeCopy.a[1] !== tree.a[1], treeCopy.d !== tree.d, treeCopy.n);

const loop = {};
loop.self = loop;

try {
  deepClone(loop);
} catch (e) {
  console.log(e.name);
}
Text
true true null
RangeError

The function returns primitives as they are, handles arrays and dates, and recurses into other objects. It does not handle maps, sets, class instances or cycles, and the cyclic input recursed until the call stack overflowed with a RangeError. To handle cycles, keep a WeakMap from original to copy, and return the existing copy when you meet an object again. Saying this in the interview shows you know where a simple solution stops.

Wrong answers that lose the point

  • "Spread makes a deep copy." It copies one level.

  • "Object.assign clones the object." It copies own enumerable properties, shallowly.

  • "JSON.parse(JSON.stringify(x)) is a perfect deep copy." It breaks dates, undefined, maps, sets, NaN, functions and cycles.

  • "A deep copy is always better." It costs time and memory, and often an immutable update of one level is enough.

A mistake we hit: a date that became a string

JavaScript
const order = { id: 1, placed: new Date("2026-01-15T10:00:00Z") };

const copy = JSON.parse(JSON.stringify(order));

console.log(order.placed.getFullYear());

try {
  console.log(copy.placed.getFullYear());
} catch (e) {
  console.log(e.name, "-", e.message);
}

console.log(structuredClone(order).placed.getFullYear());
Text
2026
TypeError - copy.placed.getFullYear is not a function
2026

We copied an order with the JSON trick before passing it to a reporting function, and the report threw because placed was now a string. The error pointed at the report and not at the copy, which cost time. structuredClone kept the Date. We now use it for plain data with dates and maps, and a clone() method for class instances.

Choosing between the techniques

You haveUse
Flat data with only primitivesSpread, Object.assign, or slice()
A nested update that changes one branchCopy each changed level with spread
Plain data with dates, maps, sets or cyclesstructuredClone()
Class instances that must keep methodsA custom clone() method
Very deep or large data updated oftenAn immutable data library such as Immer
Data made only of JSON typesstructuredClone(), or the JSON round trip if you must support old runtimes

Practical rules we follow

Use structuredClone as the default deep copy. Copy only the levels you change when updating state. Never use the JSON trick on data that may hold dates, maps, sets or undefined. Give class instances a clone() method. Test copies by checking identity at depth, copy.a.b !== original.a.b. And do not deep copy by reflex: it costs more than a shallow copy and hides intent.

Where the answer stops being enough

A deeper question covers structural sharing in persistent data structures, Object.freeze and why it is shallow, copy-on-write, transferring objects with structuredClone(value, { transfer }), and cloning in other environments such as postMessage. The reference is in the MDN structuredClone page and the HTML specification on structured serialization.

Taggedinterview
Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.