JavaScript Interview Question: Shallow Copy vs Deep Copy

A
Author
20 May, 2026 1 min read 600 views

Short answer: a shallow copy duplicates only the top level; nested objects are still shared. A deep copy duplicates every level, so changing the copy never affects the original.

const original = { name: 'Asha', address: { city: 'Pune' } };

const shallow = { ...original };      // or Object.assign({}, original)
shallow.name = 'Ravi';                // original.name still 'Asha'
shallow.address.city = 'Delhi';       // original.address.city is now 'Delhi'!

Spread, Object.assign, Array.from, slice() and [...arr] are all shallow.

Deep copy: structuredClone

const deep = structuredClone(original);
deep.address.city = 'Mumbai';         // original unaffected
  • Handles nested objects, arrays, Date, Map, Set, typed arrays and circular references.
  • Throws on functions and DOM nodes; class instances lose their prototype (become plain objects).

Why not JSON.parse(JSON.stringify(x))?

JSON.parse(JSON.stringify({ when: new Date(), fn() {}, missing: undefined }));
// { when: '2026-10-11T...' }  - Date becomes a string, function and undefined are dropped

It works for plain JSON data, but silently loses types. It also throws on circular references.

When it matters

  • React and Redux state updates: copy every level you change ({ ...state, user: { ...state.user, name } }), and leave the rest shared. That's intentional and efficient.
  • Defensive copies of configuration or cached data before mutating.
Was this article helpful?

Comments

No comments yet. Have a question or a tip? Be the first to share it.

Leave a comment

Comments are reviewed before they appear.