Skip to content
GeeksSmith
advanced 6 min read

Object Mutation & Deep Clone Internals

Deep Cloning creates an exact, independent copy of an object and all its nested references, avoiding shared object mutations while handling complex types like Date, RegExp, Map, Set, and circular references.

Why it matters in interviews

Improper cloning leads to state corruption bugs in React and Redux when nested objects are mutated by reference. Interviewers frequently test custom recursive deep clone implementations to evaluate recursion, WeakMap, and edge case handling.

Visual & Interactive Explanation

Deep Clone Strategies Comparison

Interactive Comparison

JSON.stringify / parse

Quick & Dirty

Limited
Circular RefsThrows TypeError
Dates / RegExpConverts to string
undefined / FunctionsOmitted entirely
Strengths
  • Zero external code
  • Fast for pure JSON data
Trade-offs
  • Destroys non-JSON types
  • Fails on circular refs

structuredClone()

Modern Web Standard

Native Standard
Circular RefsHandled natively
Dates / Maps / SetsCloned accurately
Functions / DOMThrows DOMException
Strengths
  • Native C++ browser speed
  • Handles circular references
Trade-offs
  • Cannot clone functions or DOM nodes

Custom WeakMap Recursive

Interview Implementation

Most Flexible
Circular RefsWeakMap cache lookup
Special TypesExplicit constructor instantiation
PerformanceO(N) traversal
Strengths
  • Fully customizable behavior
  • Interview benchmark standard
Trade-offs
  • Requires thorough edge case handling

Code Examples & Implementation

Complete Interview-Ready Deep Clone with Circular Ref Support
function deepClone<T>(obj: T, hash = new WeakMap()): T {
  // Primitives and functions
  if (Object(obj) !== obj || obj instanceof Function) {
    return obj;
  }

  // Handle circular references
  if (hash.has(obj as object)) {
    return hash.get(obj as object);
  }

  // Handle Dates
  if (obj instanceof Date) {
    return new Date(obj.getTime()) as any;
  }

  // Handle RegExp
  if (obj instanceof RegExp) {
    return new RegExp(obj.source, obj.flags) as any;
  }

  // Handle Map
  if (obj instanceof Map) {
    const result = new Map();
    hash.set(obj, result);
    obj.forEach((val, key) => {
      result.set(deepClone(key, hash), deepClone(val, hash));
    });
    return result as any;
  }

  // Handle Set
  if (obj instanceof Set) {
    const result = new Set();
    hash.set(obj, result);
    obj.forEach((val) => {
      result.add(deepClone(val, hash));
    });
    return result as any;
  }

  // Handle Arrays & Plain Objects
  const isArr = Array.isArray(obj);
  const result = (isArr ? [] : Object.create(Object.getPrototypeOf(obj))) as any;
  hash.set(obj as object, result);

  // Copy own enumerable and symbol properties
  const keys = [...Object.keys(obj), ...Object.getOwnPropertySymbols(obj as object)];
  for (const key of keys) {
    result[key] = deepClone((obj as any)[key], hash);
  }

  return result;
}

Interview-Ready Answers

A shallow copy copies top-level properties but retains references to nested objects. Deep cloning duplicates all nested objects. Modern JavaScript has `structuredClone()`, but custom implementations require recursion with a `WeakMap` for circular references.

Official Documentation & Specifications

Follow-up Questions & Deep Dives

🎯 Code Output — What Does This Print?

Question 1easy
const original = { a: 1, nested: { b: 2 } };
const shallow = { ...original };
shallow.nested.b = 99;

console.log(original.nested.b);
console.log(shallow.a === original.a);
Question 2medium
const obj = {
  date: new Date("2024-01-01"),
  fn: () => "hello",
  undef: undefined,
};

const cloned = JSON.parse(JSON.stringify(obj));
console.log(typeof cloned.date);
console.log(cloned.fn);
console.log(cloned.undef);
Question 3hard
const a = { name: "Alice" };
const b = { friend: a };
a.bestFriend = b;

try {
  const result = JSON.parse(JSON.stringify(a));
  console.log(result.name);
} catch (e) {
  console.log(e.constructor.name);
}

Common Mistakes & Anti-Patterns

  • Using JSON.parse(JSON.stringify()) in production on objects containing Dates or functions
  • Forgetting WeakMap memoization resulting in stack overflow on circular references
  • Not cloning prototype chains or symbol keys

Real-World Architectural Scenario

You are building a workflow builder where nodes reference each other cyclically. User clicks 'Duplicate Node Subtree'. How do you duplicate without infinite loops?

Rate Your Readiness

Rate how comfortably you can explain this in an interview to update your global readiness gauge:

Rate your confidence: