What is the difference between a shallow copy and a deep copy, and how do you make each one?
Objects and arrays are held by reference, so assigning one variable to another gives you two names for the same thing. Copying is how you break that.
A shallow copy duplicates the top level only. Nested objects are still shared:
const copy = { ...original };
const copy2 = Object.assign({}, original);
const arr2 = [...arr]; // or arr.slice()Change copy.user.name and the original changes too, because user is the same object in both.
A deep copy duplicates every level:
structuredClone(original)is the modern built-in answer. It handles Dates, Maps, Sets, TypedArrays, and circular references.JSON.parse(JSON.stringify(original))is the old trick, and it is lossy — it silently drops functions andundefined, turns Dates into strings, and throws on circular references.- A library such as lodash's
cloneDeepwhen you need fine control.
Note: The reason this is asked so often is React and Redux state. Mutating nested state in place means the reference does not change, so the component does not re-render.





