Algorithmsmedium

Deep clone an object

Write a `deepClone` function that creates a complete deep copy of a value, handling nested objects, arrays, dates, null, and circular references.

Asked at TikTok, Airbnb, Google

#recursion#objects#cloning

Answer

// Production approach (handles most cases)
function deepClone(value, seen = new WeakMap()) {
  if (value === null || typeof value !== 'object') return value
  if (value instanceof Date) return new Date(value)
  if (value instanceof RegExp) return new RegExp(value)

  // Handle circular references
  if (seen.has(value)) return seen.get(value)

  const clone = Array.isArray(value) ? [] : {}
  seen.set(value, clone)

  for (const key of Object.keys(value)) {
    clone[key] = deepClone(value[key], seen)
  }
  return clone
}

// Usage
const obj = { a: 1, b: { c: [1, 2, 3] }, d: new Date() }
const copy = deepClone(obj)
copy.b.c.push(4)
console.log(obj.b.c)   // [1, 2, 3] — original untouched

// Quick alternative for plain data (no Date, no undefined, no circular)
const quick = JSON.parse(JSON.stringify(obj))

// Modern: structuredClone (native, handles most types)
const native = structuredClone(obj)

Source: frontendinterviewhandbook.com

Practise more Algorithms questions →