Explain shallow copy vs deep copy. How do you clone an object correctly?
- A shallow copy creates a new top-level object, but nested objects are still shared by reference.
- A deep copy recursively copies every nested object, so the copy is fully independent.
Options
- Spread
{...obj},[...arr],Object.assignandArray.from: shallow. JSON.parse(JSON.stringify(obj)): deep, but losesundefined, functions,Symbols,Date(becomes a string),Map,Set,RegExp, and throws on circular references andBigInt.structuredClone(obj): built-in deep copy. HandlesDate,Map,Set, typed arrays,RegExpand circular references. It cannot clone functions, DOM nodes or class prototypes (instances become plain objects).
Why it matters in frontend code
React and Vue state updates rely on immutability: change a nested field by copying the path you change ({...state, user: {...state.user, name}}) instead of deep-cloning everything, which is slow and breaks memoisation for unchanged branches.
Example
js
const original = { name: 'A', tags: ['x'], created: new Date(0) };
const shallow = { ...original };
shallow.tags.push('y');
console.log(original.tags); // [ 'x', 'y' ]: shared!
const deep = structuredClone(original);
deep.tags.push('z');
console.log(original.tags.length, deep.tags.length); // 2 3
console.log(deep.created instanceof Date); // true
const viaJson = JSON.parse(JSON.stringify(original));
console.log(typeof viaJson.created); // stringFollow-up questions interviewers ask
Try answering each one before you open it.
How would you write a deep clone by hand?
Recurse over own keys, return primitives and functions as they are, create [] or {} per level, and keep a WeakMap from originals to copies so circular references and shared objects are copied once. Handle Date, Map and Set explicitly. The Frontend Coding topic has a runnable version.