PREP WITH PROOF
Menu
JAVASCRIPT & SOFTWARE ENGINEERING / PRACTICAL GUIDE

structuredClone vs JSON Deep Copy: Types, Cycles and Transfer

Choose between structuredClone, shallow copies and JSON round-trips. Test lost types, circular references, class behavior, DataCloneError and ArrayBuffer transfer.

THE QUICK ANSWER

Use structuredClone for an independent graph of supported JavaScript data, shallow copying when nested references should remain shared, and explicit JSON serialization for text interchange. Check type preservation, aliases, cycles and unsupported values. Transfer changes buffer ownership and detaches the source; it is not an ordinary copy.

Start with the copy contract, not the one-line trick

A settings editor changes a nested preference in a copied object, and the original settings change too. Replacing a spread operation with JSON.parse(JSON.stringify(value)) appears to fix that particular mutation. Later, a date becomes a string or a missing field disappears. The second failure is a different contract problem: the application asked a text serializer to preserve a JavaScript object graph.

This guide separates three decisions: create another outer container, copy supported data into an independent graph, or serialize an explicit record for storage or an API. The correct operation follows from the relationships and values the next consumer requires. A successful call alone does not establish that the output still means the same thing.

The examples below are original, small fixtures executed with Node.js v24.22.1. They test identity, mutations, exceptions and buffer ownership; they are not browser compatibility tests or performance benchmarks. Node documents structuredClone as the WHATWG operation. Check the actual runtime you deploy, especially when working with host-specific objects.

To run the examples, save the following seven code blocks together in their displayed order as clone-demo.mjs, then run node clone-demo.mjs. The first block imports Node’s built-in strict assertion module. If you run a later block on its own, include that same import at the top of its file. Successful assertions produce no output; a failure throws. No packages or network access are needed for these fixtures.

Source: Node.js: structuredClone global ↗

A new outer object can still share nested state

For a plain data object, spread creates another outer object while retaining references stored in its properties. Object.assign({}, value) likewise does not recursively copy nested objects. This can be exactly what an immutable update needs when unchanged branches are intentionally shared; it is a bug when the caller expects unrestricted independent mutation.

The first fixture makes that boundary visible. Changing the shallow copy changes the original nested value. Changing the structured clone does not. Test the nested identity directly rather than comparing only printed JSON, because equal text cannot reveal whether two properties reference the same mutable object.

Avoid replacing every shallow update with a full clone as a reflex. For a narrow state update, creating a new object only along the modified path keeps ownership explicit. For an isolated editable draft made entirely of supported cloneable data, a deep copy may be appropriate. Decide which branches may remain shared before selecting the operation.

import assert from 'node:assert/strict';

const initial = { preferences: { compact: false } };
const shallow = { ...initial };
assert.notEqual(shallow, initial);
assert.equal(shallow.preferences, initial.preferences);
shallow.preferences.compact = true;
assert.equal(initial.preferences.compact, true);

const draft = structuredClone(initial);
assert.notEqual(draft.preferences, initial.preferences);
draft.preferences.compact = false;
assert.equal(initial.preferences.compact, true);

Source: MDN: Object.assign and shallow copying ↗

What the default JSON round-trip changes

JSON is useful precisely because its output is text with a restricted data model. With no custom replacer or toJSON behavior, undefined object properties are omitted, undefined array elements become null, and nonfinite numbers become null. Date supplies its JSON representation as a string. A default Map or Set becomes an empty object rather than a record of its entries.

The next fixture deliberately groups several losses into one record so they can be checked together. It also distinguishes an absent key from a key present with undefined. That distinction can matter to a patch operation, a form default or a validation rule. Looking only at the visible value after property access would miss the difference.

For a wire payload, these transformations may be acceptable when they are part of a declared schema. For an in-memory draft, silently accepting them can create a later failure far from the cloning line. Define expected field presence, date representation and numeric ranges at the boundary. Do not treat JSON output as a faithful diagnostic dump of every JavaScript value.

const record = {
  optional: undefined,
  slots: [undefined],
  measured: NaN,
  limit: Infinity,
  at: new Date('2026-11-05T00:00:00Z'),
  counts: new Map([['ready', 2]]),
  tags: new Set(['ready'])
};
const textCopy = JSON.parse(JSON.stringify(record));
assert.equal(Object.hasOwn(textCopy, 'optional'), false);
assert.deepEqual(textCopy.slots, [null]);
assert.equal(textCopy.measured, null);
assert.equal(textCopy.limit, null);
assert.equal(typeof textCopy.at, 'string');
assert.deepEqual(textCopy.counts, {});
assert.deepEqual(textCopy.tags, {});

const dataCopy = structuredClone(record);
assert.equal(Object.hasOwn(dataCopy, 'optional'), true);
assert.equal(dataCopy.optional, undefined);
assert.equal(dataCopy.slots[0], undefined);
assert.equal(Number.isNaN(dataCopy.measured), true);
assert.equal(dataCopy.limit, Infinity);
assert.equal(dataCopy.at.getTime(), record.at.getTime());
assert.equal(dataCopy.counts.get('ready'), 2);
assert.equal(dataCopy.tags.has('ready'), true);

Source: MDN: JSON.stringify behavior ↗

Cycles and repeated references are separate tests

A cycle points back into the graph already being copied. Repeated references can exist without a cycle: two fields might both reference the same address object. The clone should be separate from the source while retaining that internal relationship when the contract requires it. WHATWG defines a remembered-object map during structured serialization for this purpose.

In the fixture, the cloned left and right properties still point to one cloned object. JSON creates two independent objects for the acyclic version, so changing one no longer updates the other. After a self-reference is added, default JSON serialization throws instead of producing text. BigInt is another independent default-JSON failure; it does not require a cycle.

These are useful regression cases for caches, editor drafts and graph-shaped application data. An equality assertion on leaf values is insufficient: check the relationships that your application uses. For API transport, represent relationships with explicit identifiers and a schema instead of assuming another service will reconstruct JavaScript identity from ordinary JSON.

const shared = { label: 'original' };
const graph = { left: shared, right: shared };
const cloned = structuredClone(graph);
assert.notEqual(cloned.left, shared);
assert.equal(cloned.left, cloned.right);
const roundTrip = JSON.parse(JSON.stringify(graph));
assert.notEqual(roundTrip.left, roundTrip.right);

graph.self = graph;
const cyclicCopy = structuredClone(graph);
assert.equal(cyclicCopy.self, cyclicCopy);
assert.equal(cyclicCopy.left, cyclicCopy.right);
assert.throws(() => JSON.stringify(graph), TypeError);
assert.equal(structuredClone(9007199254740993n), 9007199254740993n);
assert.throws(() => JSON.stringify({ id: 9007199254740993n }), TypeError);

Source: WHATWG HTML: structured serialization and graph memory ↗

A data clone does not recreate an application class

Preserving supported built-in data is different from recreating arbitrary application behavior. A custom instance with ordinary enumerable data can become a plain object: its prototype methods and private state are not reconstructed as a new working instance. Property descriptors are also not retained. Rebuild a domain object through its constructor or an explicit factory when its methods and invariants are required.

The fixture also uses a getter to demonstrate that reading a value during copying can execute code. The cloned property contains the returned value; it is not the original accessor. A frozen or readonly source property therefore does not establish the same restriction on the clone. Copying is not a general sandbox for objects whose accessors you do not control.

Function values and symbol values encountered in the cloned data cause DataCloneError. A symbol-keyed property on an ordinary object is a different case: it is omitted here. Do not summarize these behaviors as “symbols are copied” or “every symbol anywhere throws.” State which position is being tested. DOM nodes and many runtime resources also fall outside the cloning contract; check their documented support rather than adding a silent fallback.

class Ticket {
  constructor(id) { this.id = id; }
  describe() { return `Ticket ${this.id}`; }
}
const ticketCopy = structuredClone(new Ticket('T-7'));
assert.equal(ticketCopy.id, 'T-7');
assert.equal(ticketCopy instanceof Ticket, false);
assert.equal(ticketCopy.describe, undefined);

let reads = 0;
const source = {};
Object.defineProperty(source, 'score', {
  enumerable: true,
  get() { reads += 1; return 7; }
});
const accessorCopy = structuredClone(source);
assert.equal(reads, 1);
assert.equal(Object.getOwnPropertyDescriptor(accessorCopy, 'score').get, undefined);
assert.equal(Object.getOwnPropertyDescriptor(accessorCopy, 'score').writable, true);
assert.throws(() => structuredClone({ run() {} }), { name: 'DataCloneError' });
assert.throws(() => structuredClone({ value: Symbol('id') }), { name: 'DataCloneError' });
const hidden = Symbol('key');
assert.deepEqual(structuredClone({ public: 1, [hidden]: 2 }), { public: 1 });

Source: MDN: structured clone algorithm limitations ↗

ArrayBuffer copying and transfer have different ownership rules

An ordinary ArrayBuffer can be copied with its bytes. Transferring it instead makes the original buffer detached. This is a destructive ownership change for that buffer even though the surrounding input object still exists. A typed-array view is not the item to put in the transfer list; use its underlying transferable buffer.

The fixture first verifies ordinary independent copying, then transfers a different buffer shared by two views. Both source views lose access to the original backing store. This is why a helper that hides transfer inside a generic “copy” function is misleading: a caller may still be using another view of that buffer.

Use transfer only when the surrounding workflow explicitly gives up the source buffer. Do not infer a measured speedup from the option name or this small example. SharedArrayBuffer has sharing semantics and environmental requirements of its own; it is outside this ordinary ArrayBuffer fixture. A deep-copy slogan does not describe every supported type’s storage behavior.

const bytes = new Uint8Array([4, 8, 12]);
const copied = structuredClone(bytes);
copied[0] = 99;
assert.equal(bytes[0], 4);
assert.notEqual(copied.buffer, bytes.buffer);

const backing = new ArrayBuffer(3);
const firstView = new Uint8Array(backing);
const secondView = new Uint8Array(backing);
firstView.set([3, 6, 9]);
const moved = structuredClone({ bytes: firstView }, { transfer: [backing] });
assert.deepEqual(Array.from(moved.bytes), [3, 6, 9]);
assert.equal(backing.byteLength, 0);
assert.equal(firstView.byteLength, 0);
assert.equal(secondView.byteLength, 0);
assert.throws(() => new Uint8Array(backing), TypeError);

Source: MDN: ArrayBuffer ownership and detachment ↗

Design a JSON record when the destination needs JSON

A JSON replacer can encode a BigInt, but choosing a decimal string changes the schema; it does not preserve its JavaScript type automatically. Converting a large identifier to Number risks losing precision. A declared string field is easier for another consumer to validate than an undocumented conversion based on whatever value happened to arrive.

The final fixture constructs a small transport record explicitly, then reconstructs the known fields. It does not guess that every decimal-looking string should become BigInt or that every timestamp-looking string should become Date. Apply validation before reconstruction when records come from outside the application. The example assumes its own trusted fixture and is not a complete input validator.

Keep cloning failures visible. A catch block that falls back from structuredClone to a JSON round-trip changes semantics exactly when unsupported data appears. Diagnose the failing field and decide whether it belongs in an editable draft, a transport record or a separate resource owner. That decision is more useful than making the exception disappear.

const original = { id: 9007199254740993n, at: new Date('2026-11-05T00:00:00Z') };
const payload = { id: original.id.toString(), at: original.at.toISOString() };
const parsed = JSON.parse(JSON.stringify(payload));
const restored = { id: BigInt(parsed.id), at: new Date(parsed.at) };
assert.equal(restored.id, original.id);
assert.equal(restored.at.getTime(), original.at.getTime());

Source: ECMAScript: JSON.stringify specification ↗

Troubleshoot the value that breaks the contract

If DataCloneError appears, reduce the input to the smallest field that reproduces it. A function stored as a regular enumerable property is enough to fail; it does not need to be called. An object containing an enumerable toJSON method illustrates the difference: JSON can invoke that method to choose its text representation, while structuredClone encounters an unsupported function value. Do not expect the same customization hook to run for both operations.

Also check state inside otherwise supported built-ins. The fixture below preserves a regular expression’s pattern and flags but resets its lastIndex. That matters if the application expects to resume an incremental scan from an existing position. Copy that workflow state explicitly, or restart the scan deliberately. The name of a supported type is not a promise to retain every observable property.

Finally, test root-level values as well as properties. JSON.stringify(undefined) returns undefined, so passing its result to JSON.parse fails. This differs from omitting a property inside an object. When a helper sometimes receives an absent root value, decide whether absence is valid before serialization. A broad catch-and-return-empty-object policy would hide which input contract was violated.

const custom = { secret: 7, toJSON() { return { public: true }; } };
assert.deepEqual(JSON.parse(JSON.stringify(custom)), { public: true });
assert.throws(() => structuredClone(custom), { name: 'DataCloneError' });
const pattern = /ready/g;
pattern.lastIndex = 4;
const patternCopy = structuredClone(pattern);
assert.equal(patternCopy.source, pattern.source);
assert.equal(patternCopy.flags, pattern.flags);
assert.equal(patternCopy.lastIndex, 0);
assert.equal(structuredClone(undefined), undefined);
assert.equal(JSON.stringify(undefined), undefined);
assert.throws(() => JSON.parse(JSON.stringify(undefined)), SyntaxError);

Source: MDN: structuredClone and transfer options ↗

Choose and verify the operation at the boundary

Before changing an existing copy operation, list the values and reference relationships that must survive. Add one representative mutation check, one alias check and the relevant rejection or transfer case. Run them in the destination runtime. If the data crosses an API or persistence boundary, test the schema and reconstruction separately from the local copy.

The examples establish specific behavior for these fixtures, not universal performance or host-object support. Keep the smallest operation that meets the actual contract. Use deliberate shallow updates for shared branches, structuredClone for supported independent data graphs, explicit factories for application instances, and schema-driven JSON for text interchange.

NeedOperation to considerCheck before adopting
New outer record; nested references intentionally sharedSpread or Object.assignNested mutation and identity
Independent supported data graphstructuredCloneTypes, aliases, cycles and rejection cases
Application instance with behaviorExplicit constructor or factoryMethods, private state and invariants
Text for an API or storageExplicit JSON schema and serializerField presence, precision and reconstruction
Give up an ordinary bufferstructuredClone with transferEvery source view and ownership boundary
KEEP THESE THREE THINGS

Your next steps

  1. Test identities and mutations, not only equal printed values.
  2. Treat JSON field and type conversions as a schema decision; reconstruct application classes explicitly when behavior matters.
  3. Declare transfer ownership and verify all source views.

Sources & official resources

Linked resources checked on 2026-11-05. Technical behavior and provider guidance can change; check the documentation for the version you use.

About this guide and its recommendations

Published by Prep With Proof with AI-assisted drafting. Study routines and examples are editorial suggestions, not official exam instructions or claims of a learner's personal results. Cited provider facts are linked; ownership of recommended Prep With Proof products is disclosed. No competitor endorsement or guaranteed certification outcome is implied.

Suggest a correction →