What are the different ways to copy an object?

JavaScript

The 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 operator
const copy1 = { ...original };
// Object.assign
const copy2 = Object.assign({}, original);
// Both are shallow — nested objects are shared
copy1.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 affected

structuredClone 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)
  • Date objects (converted to strings)
  • Map, Set (converted to empty objects)
  • Circular references (throws an error)

Quick reference

MethodTypeHandles nestedHandles Date/Map/SetHandles circular refs
Spread {...obj}ShallowNoN/AN/A
Object.assignShallowNoN/AN/A
structuredCloneDeepYesYesYes
JSON.parse(JSON.stringify)DeepYesNoNo

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.