HomePremium · ₹1199
← All questions

Deep clone an object

Hard
Asked at:AtlassianFlipkart
Was this asked in an interview?

Recursively deep-clone nested objects and arrays without mutating the source.

Problem

Implement deepClone(value) that returns a completely independent copy of value.

Shallow copies ({...obj}, Object.assign, [...arr]) only copy the top level — nested objects and arrays are still shared references, so mutating the copy corrupts the original. You need a recursive clone for safely snapshotting state (undo/redo, immutable updates, caching API responses).

deepClone(value) must:

  • Return primitives (string, number, boolean, null, undefined, symbol, bigint) unchanged.
  • Recursively clone arrays and plain objects.
  • Never mutate the source, and never share nested references with it.

Input

const original = { a: 1, b: { c: 2, d: [3, { e: 4 }] } };
const copy = deepClone(original);
copy.b.d[1].e = 99;

Expected output

  • original.b.d[1].e is still 4 (source untouched)
  • copy.b.d[1].e is 99

Implement from scratch (no structuredClone / JSON.parse(JSON.stringify(...))):

function deepClone(value) {
  // Your code here
}
Deep clone an object — JavaScript Interview Question | Mentoxis