Question presented to candidate: "If your object has a circular reference — an object that references itself somewhere inside its own nested structure — would JSON.parse(JSON.stringify(obj)) work to deep clone it? What would you actually use instead?"
What a strong answer should cover:
- 📌 Interview term: shallow copy vs. deep clone — a shallow copy (
{ ...obj },Object.assign) only copies the TOP-level properties; any NESTED object/array is still the SAME shared reference — verified directly: mutating a nested value through a shallow copy genuinely leaked back and changed the original. - 📌 Interview term: the real, direct answer to the prompt — verified directly:
JSON.stringify()genuinely throws a realTypeErroron a circular reference — it cannot serialize an object that references itself, soJSON.parse(JSON.stringify(obj))is not just imperfect for circular structures, it genuinely fails outright. - 📌 Interview term:
structuredClone()— the modern, native, built-in deep-clone function — verified directly: it genuinely produces fully independent, deeply-copied nested references (a mutation on the clone genuinely does NOT leak back to the original), and it genuinely handles a circular reference correctly, with no error. - 📌 Interview term: what
structuredClonecan and can't clone — verified directly: it correctly preserves realDateobjects as actualDateinstances (unlikeJSON.stringify, which turns aDateinto a plain string, verified directly as a second, real advantage over the JSON trick) — but it genuinely throws on a function, since code itself cannot be cloned. - A precise answer names that
JSON.parse(JSON.stringify())remains a real, valid quick option specifically when the data is known in advance to be plain, JSON-safe data (no functions, noDates, no circular references, noundefinedvalues) — otherwisestructuredClone()is the correct, modern, general-purpose tool.
Clarifying questions expected:
- None — this is a definitional/technical question; directly answering the prompt's circular-reference scenario (and naming the correct modern fix) is the strong signal.
Code / implementation expected: Yes — the real circular-reference test (JSON throwing vs. structuredClone succeeding) is the clearest, most convincing demonstration.