Emmanuel Akinfulubi

JavaScriptBasic

Deep clone an object in JavaScript

Advanced · 4 min read

Sometimes you need a copy of an object that you can change freely without touching the original. An "edit profile" form works on a copy so the user can cancel. An undo feature keeps copies of earlier states. A test makes a copy of some sample data before changing it. If the copy secretly shares parts with the original, a change to one shows up in the other, and the bug is hard to trace.

In this tutorial you will try three ways of copying a nested object: the spread syntax, a trip through JSON, and the built-in structuredClone. You will see exactly what each one gets wrong or right. You need to know what an object, an array and a variable are.

Objects are shared, not copied

When you assign an object to a new variable, you don't get a copy. Both variables point at the same object:

JavaScript

const a = { sold: 9 };
const b = a;
b.sold = 999;
console.log(a.sold); // 999

The variable holds a reference, which you can think of as the object's address. b = a copies the address, not the object. So there is only one object, with two names.

Shallow and deep

A shallow copy makes a new outer object, but anything inside it that is itself an object is still shared. A deep copy makes new objects all the way down, so nothing is shared.

Here is the object the exercise copies. It has a nested object, a date, an array and a property set to undefined:

JavaScript

const original = {
  plate: 'LAG-441-XA',
  seats: { total: 14, sold: 9 },
  serviced: new Date('2026-01-15T00:00:00Z'),
  tags: ['aircon', 'wifi'],
  notes: undefined,
};
console.log(Object.keys(original)); // [ 'plate', 'seats', 'serviced', 'tags', 'notes' ]

Here is the exercise. Try it yourself first if you like, or follow the steps.

40 Deep clone an object

hard

Copy a nested object so that changing the copy cannot affect the original. Show what the shallow and JSON approaches lose.

Stuck? Three hints, smallest first
  1. 1. Spreading copies one level only: nested objects stay shared.
  2. 2. JSON.parse(JSON.stringify(x)) goes deep but destroys dates, maps, undefined and functions.
  3. 3. structuredClone is the built-in that handles most of it.

Step 1: the spread copy is shallow

{ ...original } copies each top-level property into a new object. That looks like a copy, and for plate it is. But seats holds a reference, and the reference is what gets copied:

JavaScript

const original = { plate: 'LAG-441-XA', seats: { total: 14, sold: 9 } };
const shallow = { ...original };
shallow.plate = 'NEW-PLATE';
shallow.seats.sold = 999;
console.log(original.plate);      // LAG-441-XA: top level is separate
console.log(original.seats.sold); // 999: the nested object is shared

Changing shallow.plate left the original alone. Changing shallow.seats.sold changed the original too, because there is only one seats object. Spread is fine for flat objects, and a trap for nested ones.

Step 2: the JSON round trip is deep but lossy

JSON.stringify turns an object into text, and JSON.parse builds a brand-new object from that text. Nothing can be shared, because everything is rebuilt:

JavaScript

const original = {
  seats: { total: 14, sold: 9 },
  serviced: new Date('2026-01-15T00:00:00Z'),
  notes: undefined,
};
const viaJson = JSON.parse(JSON.stringify(original));
viaJson.seats.sold = 1;
console.log(original.seats.sold);     // 9: properly separate
console.log(typeof viaJson.serviced); // string: the Date became text
console.log('notes' in viaJson);      // false: the undefined key is gone

JSON only knows text, numbers, booleans, null, arrays and plain objects. A Date is written as text and comes back as a string. A property set to undefined is left out completely. Maps, Sets and functions are lost too. Nothing warns you. The damage shows up later, when some code calls .getFullYear() on what it thinks is a date.

Step 3: structuredClone is deep and faithful

structuredClone is built into modern JavaScript for exactly this job. It copies all the way down and keeps dates, Maps, Sets, undefined values and even objects that refer to themselves:

Step 3

const original = {
  plate: 'LAG-441-XA',
  seats: { total: 14, sold: 9 },
  serviced: new Date('2026-01-15T00:00:00Z'),
  tags: ['aircon', 'wifi'],
  notes: undefined,
};
const deep = structuredClone(original);
deep.seats.sold = 1;
deep.tags.push('tv');
console.log(original.seats.sold);         // 9
console.log(original.tags);               // [ 'aircon', 'wifi' ]
console.log(deep.serviced instanceof Date); // true
console.log('notes' in deep);             // true
console.log(deep === original);           // false

Changing the nested object and pushing to the nested array left the original untouched. instanceof Date checks that the copied date is still a real Date, and it is.

Step 4: what structuredClone can't copy

There is one kind of value it refuses: functions.

JavaScript

try {
  structuredClone({ greet() { return 'hi'; } });
} catch (err) {
  console.log(err.name); // DataCloneError
}

It throws an error instead of silently dropping the function, which at least tells you straight away. For plain data, which is what you usually copy, that limit rarely matters.

Which one to use

  • The object is flat (no objects inside): { ...original } is fine.
  • The object is nested: structuredClone(original).
  • Avoid the JSON round trip for copying, unless you know the data holds only text, numbers, booleans, arrays and plain objects.

The full solution

The complete answer copies the same bus record three ways. It shows the shallow copy leaking a change into the original, the JSON copy turning the date into a string and dropping notes, and structuredClone keeping everything separate and intact. Press Run to see the output.

The answer

const original = {
  plate: 'LAG-441-XA',
  seats: { total: 14, sold: 9 },
  serviced: new Date('2026-01-15T00:00:00Z'),
  tags: ['aircon', 'wifi'],
  notes: undefined,
};

// One level only. The nested object is shared.
const shallow = { ...original };
shallow.seats.sold = 999;
console.log('after editing the shallow copy, original sold =', original.seats.sold);
original.seats.sold = 9;                 // put it back

// Deep, but lossy.
const viaJson = JSON.parse(JSON.stringify(original));
console.log('date became a', typeof viaJson.serviced);
console.log('undefined key survived?', 'notes' in viaJson);

// Deep and faithful.
const deep = structuredClone(original);
deep.seats.sold = 1;
deep.tags.push('tv');

console.log('original sold after deep edit:', original.seats.sold);
console.log('original tags after deep edit:', original.tags);
console.log('date is still a Date:', deep.serviced instanceof Date);

Output


      
8 checks that prove this answer

You do not have to read these. They are part of the answer panel above, so pressing Run there executes all 8 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

8 checks

test('the shallow copy shared the nested object', original.seats.sold, 9);
test('JSON turns a Date into text', typeof viaJson.serviced, 'string');
test('JSON drops undefined keys', 'notes' in viaJson, false);
test('structuredClone keeps the Date', deep.serviced instanceof Date, true);
test('and keeps the undefined key', 'notes' in deep, true);
test('a deep edit leaves the original alone', original.seats.sold, 9);
test('and so does a nested array push', original.tags, ['aircon', 'wifi']);
test('but it is a different object', deep === original, false);

Three tools, three different failure modes. Spreading is fine when the object is one level deep and a trap otherwise. The JSON round trip is deep but silently converts dates to strings and deletes undefined values, which is the sort of thing that surfaces days later. structuredClone is built in, handles dates, maps, sets and cycles, and cannot copy functions — which is usually what you want anyway.

Common mistakes

  • Thinking const b = a makes a copy. It gives the same object a second name.
  • Using spread on nested data. Only the top level is new. Inner objects and arrays are still shared.
  • Using JSON to clone objects with dates. The dates come back as strings, and undefined properties vanish.

Try it yourself

  1. Copy an array of objects, [{ id: 1 }, { id: 2 }], with [...list]. Change copy[0].id. What happens to the original, and why?
  2. Use structuredClone on a Map and check that the copy is still a Map.
  3. Make an object that refers to itself (const o = {}; o.self = o;). What happens when you try JSON.stringify(o), and what does structuredClone(o) do?

Keep practising

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.