JavaScriptFundamental (ES6), part 1
structuredClone vs spread copy in JavaScript
81 structuredClone against a spread copy
fairCopy an order two ways — with a spread and with structuredClone — then change something nested in each copy and see which original moved. Check what the deep copy does with a Map, a Date and a cycle, then find the two things it will not do: keep a class prototype, and carry a function.
Stuck? Three hints, smallest first
- 1. A spread copies one level. Nested objects are the same objects, shared between copy and original.
- 2.
structuredClonewalks the whole structure, remembers what it has seen, and so survives a cycle thatJSON.stringifycannot. - 3. It copies data, not behaviour: a function makes it throw, and a class instance comes back as a plain object.
class Buyer {
constructor(name) {
this.name = name;
}
shout() {
return this.name.toUpperCase();
}
}
const order = {
ref: 'IK-104',
buyer: new Buyer('Adaeze'),
address: { lga: 'Ikeja', street: 'Allen' },
goods: ['garri', 'rice'],
placed: new Date(0),
counts: new Map([['garri', 2]]),
seen: new Set(['garri']),
note: undefined,
};
const shallow = { ...order };
const deep = structuredClone(order);
shallow.address.street = 'Awolowo';
const originalMovedWithShallow = order.address.street;
deep.address.street = 'Toyin';
const originalIgnoredDeep = order.address.street;
const sharedReferences = [shallow.address === order.address, deep.address === order.address];
deep.goods.push('beans');
const goodsStayed = order.goods.length;
const dateSurvived = [deep.placed instanceof Date, deep.placed.getTime()];
const collectionsSurvived = [deep.counts instanceof Map, [...deep.counts], deep.seen.has('garri')];
const undefinedSurvived = ['note' in deep, deep.note === undefined];
const cyclic = { lga: 'Ikeja' };
cyclic.itself = cyclic;
const clonedCycle = structuredClone(cyclic);
const cycleHeld = [clonedCycle.itself === clonedCycle, clonedCycle !== cyclic];
let jsonOnCycle;
try {
JSON.stringify(cyclic);
} catch (error) {
jsonOnCycle = error.constructor.name;
}
const prototypeLost = [order.buyer.shout(), deep.buyer instanceof Buyer, deep.buyer.name, typeof deep.buyer.shout];
let withFunction;
try {
structuredClone({ price: () => 1 });
} catch (error) {
withFunction = error.name;
}
const throughJson = JSON.parse(JSON.stringify({ placed: new Date(0), note: undefined, counts: new Map([['a', 1]]) }));
const jsonFlattens = [typeof throughJson.placed, 'note' in throughJson, throughJson.counts];
console.log('shallow:', originalMovedWithShallow, '| deep:', originalIgnoredDeep);
console.log('shared :', sharedReferences, '| goods:', goodsStayed);
console.log('kept :', dateSurvived, collectionsSurvived, undefinedSurvived);
console.log('lost :', prototypeLost, withFunction, '| json:', jsonFlattens);
Output
9 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 9 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('a nested write through a spread copy is a write to the original', [originalMovedWithShallow, sharedReferences], ['Awolowo', [true, false]]);
test('the deep copy is genuinely separate, arrays included', [originalIgnoredDeep, goodsStayed], ['Awolowo', 2]);
test('a Date comes back as a Date, not as a string', dateSurvived, [true, 0]);
test('and a Map and a Set come back as themselves', collectionsSurvived, [true, [['garri', 2]], true]);
test('an explicit undefined property is kept, key and all', undefinedSurvived, [true, true]);
test('a cycle is fine, where JSON.stringify gives up', [cycleHeld, jsonOnCycle], [[true, true], 'TypeError']);
test('but the prototype is dropped: the data survives, the methods do not', prototypeLost, ['ADAEZE', false, 'Adaeze', 'undefined']);
test('and a function anywhere in the structure makes it throw', withFunction, 'DataCloneError');
test('a JSON round trip loses more still: a Date becomes text, undefined vanishes, a Map empties', jsonFlattens, ['string', false, {}]);
Three copies, three different meanings. A spread or Object.assign duplicates the top level and shares everything below it, which is exactly right for an immutable update where you rebuild only the branch you touched, and exactly wrong when you meant "give me my own copy". structuredClone walks the whole graph and remembers what it has already copied, so cycles and shared references survive as the same shape rather than being duplicated or hanging.
What it cannot do follows from what it is: a data-only serialiser. Prototypes are dropped, so a class instance comes back as a plain object with the right fields and no methods; functions, DOM nodes and symbols make it throw a DataCloneError; getters are read and stored as flat values. Anything with behaviour needs a real clone() or a factory that rebuilds the instance.
Against the old JSON.parse(JSON.stringify(x)) trick it is not close. That one turns a Date into a string, empties a Map and a Set into {}, drops undefined, functions and symbols, mangles NaN and Infinity into null, and throws on a cycle. It is still the fastest way to snapshot plain JSON-shaped data, and it is the wrong tool for anything else.