Deep Clone vs Shallow Copy: Interview Answers
JS جاوااسکریپت

Deep Clone vs Shallow Copy: Interview Answers

Object.assign, spread, structuredClone, and JSON pitfalls — know what each actually copies.

BugCast Admin··۵ دقیقه مطالعه

Copying objects sounds simple until nested references, Dates, Maps, and circular structures appear. Interviewers want precise trade-off answers.

Common Interview Questions

Q: Shallow vs deep copy?

Answer: Shallow copy duplicates top-level properties but shares nested object references. Deep copy recursively clones nested structures so mutations do not cross copies.

Q: Why is JSON.parse(JSON.stringify(obj)) risky?

Answer: Loses undefined, functions, Symbols, Dates (become strings), Maps/Sets, and fails on circular references. Fine for plain JSON data only.

Q: What is structuredClone?

Answer: Built-in deep clone supporting Dates, RegExp, Map, Set, ArrayBuffer, and circular references in modern environments. Still cannot clone functions or DOM nodes.


const copy = structuredClone(original);

Q: Immutable update of nested state?

Answer: Spread each level you change. Libraries like Immer simplify deep updates by drafting mutable copies behind the scenes.


const next = {
  ...state,
  user: { ...state.user, name: "New" },
};

Key Points for Interviews

  • Spread and Object.assign are shallow

  • structuredClone is the modern default for deep clone

  • JSON trick is quick but lossy

  • Libraries like lodash cloneDeep for legacy support

  • React state updates require immutability at changed paths

#clone#immutability#interview

مطالب مرتبط