Skip to the page

Utility functions · mid

Deep clone and deep equal

A hand-written deep clone recursively copies arrays and plain objects (plus Date, Map, Set and RegExp when asked) and uses a WeakMap of already-copied objects to handle cycles; deep equal compares type, then keys and values recursively, with care for NaN, +0/−0, arrays vs objects and cycles.

The notes

What you must know

  • Ask about scope first: cycles? class instances? symbols? functions? (The Frontend Interview Handbook says to clarify cycles; usually they are out of scope.)
  • Clone: return primitives and functions as they are; Date -> new Date(d); RegExp -> new RegExp(source, flags); Map and Set -> copy entries recursively; arrays and objects -> make the container, store it in the seen WeakMap, then recurse.
  • The seen WeakMap handles both cycles and shared references.
  • Keeping prototypes (Object.create(Object.getPrototypeOf(obj))) and symbol keys (Reflect.ownKeys) are optional extras to discuss.
  • In production use structuredClone (know its limits) or lodash cloneDeep.
  • deepEqual: Object.is first; different types or array-vs-object -> false; compare key counts and every own key recursively; compare Date and RegExp by value; for cycles keep a map of pairs already compared.
  • O(n) over all nodes. Very deep data can overflow the stack; an explicit stack avoids that.

The red pen

Common traps: mistake → fix

  • Mistake: typeof null === 'object'

    Fix: check null first.

  • Mistake: No cycle handling

    Fix: stack overflow.

  • Mistake: Treating [] and {} as equal, or comparing with JSON.stringify (key order, undefined and NaN problems).

Easy to hard

Questions interviewers ask, easy to hard

  1. Write deepClone for objects and arrays.
  2. Add Date, Map, Set and circular references.
  3. When would you just use structuredClone?
  4. Write isEqual(a, b). How do you handle NaN, +0/-0, key order and cycles?

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview