Skip to main content

Search

Search problems, hooks, and pages

Deep Clone an Object

Write a function deepClone(obj) that returns a completely independent deep copy of an object — modifying the clone must not affect the original. This tests your understanding of reference types, recursion, and knowledge of JavaScript's special object types (Date, RegExp, Map, Set, circular references).

Examples

Input: { a: 1, b: { c: 2 } }
Output: { a: 1, b: { c: 2 } } (different reference)
// clone.b !== original.b — the nested object is also a new copy.
Input: { date: new Date("2024-01-01") }
Output: { date: Date(2024-01-01) } (new Date instance)
// Date must be cloned as a new Date — not just copied as reference.
Input: Circular reference: a.self = a
Output: Cloned object with clone.self === clone (circular preserved)
// Naive recursive clone throws on circular references.

Constraints

  • Handle primitives, plain objects, and arrays.
  • Bonus: handle Date, RegExp, Map, Set.
  • Bonus: handle circular references without infinite recursion.
recursionobjectWeakMapreference-typesstructuredClone

Important

Interview Tip

Start with structuredClone (modern built-in) to show knowledge, then mention JSON round-trip and its limits (drops functions, Date becomes string, no circular). Implement recursively for the "real" answer. The circular reference follow-up is very common — use WeakMap as a "seen" cache.

Approach: Brute Force (JSON)

JSON.parse(JSON.stringify(obj)) — the classic one-liner. Works for plain JSON-safe data but drops functions, converts Dates to strings, and throws on circular references.

Complexity

Time: O(n)Space: O(n)

Pros

  • One line
  • Simple to remember
  • Good for plain data

Cons

  • Drops: functions, undefined, RegExp, Symbol
  • Date becomes string
  • Throws on circular references