Beginner JavaScript Interview QuestionsBeginnerComparison
JavaScript · Question 25
What is the difference between a shallow copy and a deep copy in JavaScript?
Direct answer
A shallow copy duplicates only the outer container while nested object references remain shared; a deep copy recursively creates independent nested values where cloning is supported.
Array spread, object spread, Array.from(), and common uses of Object.assign() create shallow copies. That means top-level properties are copied, but nested objects can still point to the same object.
With const a = { profile: { name: 'A' } }; const b = { ...a };, changing b.profile.name also affects what a.profile.name reads because profile is shared.
- Use a shallow copy when nested sharing is acceptable or nested values are treated immutably.
- For supported data, structuredClone() can create a deep clone of many built-in types.
- JSON stringify/parse is not a general-purpose deep clone because it loses or rejects several JavaScript value types.