Arrays, collections and copying · core
Shallow copy, deep copy and structuredClone
Spread and Object.assign copy only the top level; structuredClone makes a real deep copy of plain data (including Map, Set, Date and cycles) but throws on functions and DOM nodes and drops prototypes, getters and property flags.
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceThe notes
What you must know
- Assignment copies the reference. Spread, Object.assign, Array.from and slice copy one level; nested objects stay shared.
- JSON.parse(JSON.stringify(x)) loses data: undefined, functions and symbols are dropped from objects (null in arrays); Dates become strings; Map and Set become {}; NaN and Infinity become null; BigInt and cycles throw.
- structuredClone (Baseline since 2022, Node 17+) deep-copies plain objects, arrays, Map, Set, Date, RegExp, typed arrays, standard Error types and Blob/File, and keeps cycles and shared references.
- structuredClone throws DataCloneError for functions (including methods on the object), DOM nodes and symbols. It does not copy the prototype chain (a class instance comes back as a plain object without its methods), turns getters into plain values, resets property flags and skips #private fields.
- The same structured clone algorithm is used by postMessage (workers, iframes), IndexedDB and history.pushState.
- The transfer option moves ArrayBuffers instead of copying them; the original becomes unusable (byteLength 0).
- Immutability matters for React and Redux: create new objects when something changes so a === check detects it. Immer lets you write 'mutations' on a draft and produces a new object.
The red pen
Common traps: mistake → fix
Mistake: structuredClone keeps methods
Fix: a function anywhere in the value makes it throw DataCloneError; class instances lose their methods.
Mistake: Spread is a deep copy
Fix: it copies one level.
Mistake: JSON round-tripping is a safe deep copy
Fix: it silently changes or drops many value types.
Mistake: Object.freeze gives an immutable copy
Fix: it freezes the same object, shallowly.
Easy to hard
Questions interviewers ask, easy to hard
- How do you copy an object? Shallow vs deep.
- What does JSON.parse(JSON.stringify(obj)) lose?
- What can't structuredClone copy? What happens to a class instance?
- Why does immutability matter for React state and Redux?
- Where else is the structured clone algorithm used, and what does transfer do?
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceYour first interview is free
Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.