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.