What are the different ways to copy an object?
JavaScriptThe short answer
For shallow copies, use the spread operator ({ ...obj }) or Object.assign(). For deep copies, use structuredClone(). JSON.parse(JSON.stringify()) works for simple objects but fails with dates, functions, and circular references. Always know whether you need a shallow or deep copy.
Shallow copy methods
A shallow copy duplicates the top-level properties. Nested objects are still shared by reference.
const original = { name: 'John', address: { city: 'NYC' } };// Spread operatorconst copy1 = { ...original };// Object.assignconst copy2 = Object.assign({}, original);// Both are shallow — nested objects are sharedcopy1.address.city = 'Boston';console.log(original.address.city); // "Boston" — original changed!Deep copy methods
A deep copy duplicates everything, including nested objects.
structuredClone (recommended):
const original = { name: 'John', address: { city: 'NYC' }, date: new Date(),};const deep = structuredClone(original);deep.address.city = 'Boston';console.log(original.address.city); // "NYC" — not affectedstructuredClone handles nested objects, arrays, dates, maps, sets, and circular references.
JSON.parse + JSON.stringify (limited):
const deep = JSON.parse(JSON.stringify(original));This works for plain objects with strings, numbers, booleans, arrays, and nested objects. It fails with:
undefined(dropped)- Functions (dropped)
Dateobjects (converted to strings)Map,Set(converted to empty objects)- Circular references (throws an error)
Quick reference
| Method | Type | Handles nested | Handles Date/Map/Set | Handles circular refs |
|---|---|---|---|---|
Spread {...obj} | Shallow | No | N/A | N/A |
Object.assign | Shallow | No | N/A | N/A |
structuredClone | Deep | Yes | Yes | Yes |
JSON.parse(JSON.stringify) | Deep | Yes | No | No |
Interview Tip
Show spread for shallow copies and structuredClone for deep copies. Explain why JSON.parse(JSON.stringify) is not reliable. The comparison table makes the differences clear at a glance.
Why interviewers ask this
Copying objects correctly is essential for avoiding mutation bugs, especially in React where immutability matters. Interviewers want to see if you know the difference between shallow and deep copies and can pick the right method.