Deep copies with structuredClone
A deep copy duplicates every level: the outer object, the objects it holds, the objects those hold, and the arrays in between. The spread of the previous lesson copies one level and shares the rest, which is fine for a settings object and wrong for a document tree, where a write three levels down would reach the original. JavaScript gained structuredClone for the full job: it is a global function in every current runtime, Node.js included.
The function copies data and refuses code. A function, a class method or an error inside the value stops the call with a DataCloneError, and a class instance comes back as a plain object with the same properties and no prototype. The older JSON round trip is still in use and loses even more, so this lesson puts the two next to each other.
Why a shallow copy is not enough
The previous lesson ended with an object whose inner address was still shared between the original and the copy. Changing copy.address.city printed Paris from original.address.city, because both objects held the same address. The fix is not a second spread: writing { ...original, address: { ...original.address } } works for one known field and stops working at the next level, and it needs a new line for every field.
What is needed is a function that walks the value and repeats the copy wherever it meets another object. That walk has to know about arrays, dates, maps and sets, has to keep shared references shared inside the clone, and must not loop forever on a value that contains itself. structuredClone is that function, and the platform ships it.
structuredClone
structuredClone(value) returns a clone of the value: plain objects, arrays, Date, Map, Set, RegExp, typed arrays and buffers are cloned with their contents, and a value that holds itself is cloned once with the cycle kept. The program below clones an object with a nested object, an array and a date, then changes the clone.
const original = {
name: 'Ada',
address: { city: 'London' },
tags: ['math', 'code'],
born: new Date('1815-12-10T00:00:00Z'),
};
const copy = structuredClone(original);
copy.address.city = 'Paris';
copy.tags.push('analytical engine');
console.log('city:', original.address.city);
console.log('tags:', original.tags.join(', '));
console.log('new nested object:', original.address !== copy.address);
console.log('date kept:', copy.born instanceof Date);
console.log('born:', copy.born.toISOString());
node deep.mjs
city: London
tags: math, code
new nested object: true
date kept: true
born: 1815-12-10T00:00:00.000Z
Every write went into the clone: the city stayed London, the tags stayed two, and the address in the clone is a different object from the one in the original. The date is the part a JSON round trip cannot do: it came back as a Date, not as text, and still answers toISOString.
What structuredClone refuses
The function implements the structured clone algorithm, and that algorithm carries data, not code. A property whose value is a function makes the whole call fail with a DataCloneError, and the message names the function it found. A class instance is data, so it is cloned property by property into a plain object: the prototype is not copied, which means the methods are gone and instanceof answers false.
const withFunction = { name: 'run', action: () => 'ran' };
try {
structuredClone(withFunction);
} catch (error) {
console.log(error.name + ': ' + error.message);
}
class Point {
constructor(x, y) {
this.x = x;
this.y = y;
}
length() {
return Math.hypot(this.x, this.y);
}
}
const point = new Point(3, 4);
const clone = structuredClone(point);
console.log('clone:', JSON.stringify(clone));
console.log('instanceof Point:', clone instanceof Point);
console.log('method kept:', typeof clone.length);
node limits.mjs
DataCloneError: () => 'ran' could not be cloned.
clone: {"x":3,"y":4}
instanceof Point: false
method kept: undefined
The clone holds the two numbers and nothing else, so a class that has to survive a copy needs a method of its own, such as copy() that builds new Point(this.x, this.y). Symbols, promises, weak maps and DOM nodes are refused in the same way as functions.
The JSON round trip
Before structuredClone, the common deep copy was JSON.parse(JSON.stringify(value)). It works on plain data and only on what JSON can express, so a date becomes a string, a property whose value is undefined disappears, and a set becomes an empty object. The program below copies one object both ways and reads the losses from the copy.
const original = {
name: 'Ada',
born: new Date('1815-12-10T00:00:00Z'),
note: undefined,
tags: new Set(['math']),
};
const copy = JSON.parse(JSON.stringify(original));
console.log('born type:', typeof copy.born);
console.log('born:', copy.born);
console.log('note kept:', 'note' in copy);
console.log('tags:', JSON.stringify(copy.tags));
node json.mjs
born type: string
born: 1815-12-10T00:00:00.000Z
note kept: false
tags: {}
The date survives as text, so a later getFullYear() on it throws; the property with undefined is gone rather than undefined; the set is a plain object with no entries. The round trip is still the right tool for plain data that will be sent as JSON anyway, and for a copy in memory it is the wrong one.
Exercises
- Add a Map and a Set to the object in deep.mjs and print their sizes from the clone. Are the contents there?
- Set original.self = original; in deep.mjs before the clone and print copy.self === copy. What does the clone do with the cycle?
- Add born as a Date to the JSON program and print copy.born instanceof Date. What is the answer, and why?
- Clone an object that has a symbol key in limits.mjs and print the keys of the clone. Which keys arrived?
- Build an array of ten thousand small objects, clone it with structuredClone and with the JSON round trip, and compare the time with console.time and console.timeEnd.
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What does
structuredClonecopy?Answer
Every level, including nested arrays, dates, maps and sets
It walks the whole value and clones each supported type, which is what makes it a deep copy.
-
What does this program print?
const original = { inner: { n: 1 } }; const copy = structuredClone(original); copy.inner.n = 2; console.log(original.inner.n);Answer
1
The clone has its own inner object, so the write through it never reaches the original.
-
What does this program print?
const original = { when: new Date("2026-01-01T00:00:00Z") }; const copy = structuredClone(original); console.log(copy.when instanceof Date);Answer
true
structuredClone keeps a Date a Date, which is the difference from the JSON round trip.
-
What happens when a cloned object holds a function?
Answer
The call throws a DataCloneError
The structured clone algorithm carries data only, so a function property stops the whole call.
-
What does this program print?
class Point { constructor() { this.x = 1; } } const point = new Point(); const clone = structuredClone(point); console.log(clone instanceof Point);Answer
false
The clone is a plain object with the same properties, and the prototype of the class is not copied.
-
What does this program print?
const copy = JSON.parse(JSON.stringify({ n: 1, note: undefined })); console.log(Object.keys(copy).join(", "));Answer
n
JSON has no undefined, so the property is left out of the text and never comes back.
-
Which value changes its type in a JSON round trip?
Answer
A Date
A Date is written as an ISO string, so it comes back as a string and its date methods are gone.
-
Why is a second spread not a deep copy?
Answer
Because it copies one level and keeps the references inside
The copy has its own top-level properties, and every object inside is still the one from the original.
-
What does this program print?
const value = { run: () => 1 }; try { structuredClone(value); } catch (error) { console.log(error.name); }Answer
DataCloneError
A function cannot be cloned, and the name of the error the platform throws is DataCloneError.
-
What does
structuredClonedo with an object that contains itself?Answer
It clones it once and keeps the cycle inside the clone
The algorithm tracks the values it has already visited, so a cycle becomes a cycle in the clone instead of an endless walk.
The code on this page was run with Node.js 24.22.1 and linted with ESLint 10.14.0 on Alpine Linux 3.24.3 (x86_64) in a Docker container.
Article author: Arthur Isaev