Sub topic 5
Which Types structuredClone Can Copy
This chapter assumes you know JavaScript objects, arrays and primitive types, and the basics of Map, Set and Date. It also assumes you have read the earlier chapter that introduced structuredClone(value). Every example runs in a modern browser console or in Node.js 17 or later.
The structured clone algorithm does not copy "anything you throw at it." It works from a fixed list of types. For each type on the list, the specification says exactly which parts of the value are recorded and how the copy is rebuilt. If you know that list and the rules for each entry, you can predict what a copy will look like before you make it.
How the algorithm decides what to do
When structuredClone meets a value, it checks what kind of value it is and picks one serialization rule. Primitives are copied as they are. Recognized built-in objects get a type-specific rule. Plain objects and arrays have their own enumerable properties walked one by one. Anything else causes an error.
The chapter "Functions, DOM Nodes and DataCloneError" covers the error branch. This chapter covers what happens on the branches that succeed.
The supported types at a glance
| Category | Types | What the copy keeps |
|---|---|---|
| Primitives | `undefined`, `null`, boolean, number, bigint, string | The exact value, including `-0`, `NaN` and `Infinity` |
| Wrapper objects | `Boolean`, `Number`, `BigInt`, `String` objects | The wrapped primitive and the wrapper type |
| Dates | `Date` | The time value, including invalid dates |
| Regular expressions | `RegExp` | `source` and `flags` only |
| Binary data | `ArrayBuffer`, `DataView`, all typed arrays | Bytes, view type, `byteOffset` and length |
| Collections | `Map`, `Set` | Entries in insertion order, with keys and values cloned |
| Containers | `Array`, plain `Object` | Own enumerable string-keyed properties |
| Errors | `Error`, `EvalError`, `RangeError`, `ReferenceError`, `SyntaxError`, `TypeError`, `URIError` | Error type, `message`, usually `stack` |
| Browser platform objects | `Blob`, `File`, `FileList`, `ImageData`, `ImageBitmap`, `CryptoKey`, `DOMMatrix`, `DOMPoint` and others | Depends on the type; availability varies by runtime |
The rest of the chapter goes through these rows one at a time and points out where the copy differs from what you might expect.
Primitives
Every primitive except symbol is copied exactly. This is the first big difference from a JSON round-trip, which cannot represent undefined, NaN, Infinity, -0 or bigints.
const values = [undefined, null, true, 42, -0, NaN, Infinity, 10n, 'text'];
const copies = structuredClone(values);
console.log(copies[0] === undefined); // true
console.log(Object.is(copies[4], -0)); // true
console.log(Number.isNaN(copies[5])); // true
console.log(copies[6] === Infinity); // true
console.log(typeof copies[7]); // 'bigint'Primitives are immutable, so a "copy" of a primitive cannot be told apart from the original. This rule matters mostly because primitives sit inside the containers you clone.
Wrapper objects
Writing new String('hi') or Object(5n) creates an object that wraps a primitive. The algorithm recognizes these wrapper objects and rebuilds a wrapper of the same type around the same primitive.
const boxed = structuredClone(new String('hi'));
console.log(typeof boxed); // 'object'
console.log(boxed instanceof String); // true
console.log(boxed.valueOf()); // 'hi'
console.log(boxed === 'hi'); // false
const big = structuredClone(Object(10n));
console.log(typeof big, big.valueOf()); // 'object' 10nYou rarely create wrappers on purpose. When one turns up in your data, though, it stays a wrapper in the copy. It does not get unwrapped into a primitive.
Dates
A Date is stored as a single number, its time value in milliseconds since the epoch. The clone is a new Date with the same time value. An invalid date stays invalid. A JSON round-trip handles this badly: JSON.stringify(new Date(NaN)) produces null.
const valid = new Date('2026-11-25T10:00:00Z');
const invalid = new Date('not a date');
const copy = structuredClone({ valid, invalid });
console.log(copy.valid instanceof Date); // true
console.log(copy.valid.getTime() === valid.getTime()); // true
console.log(copy.valid === valid); // false
console.log(Number.isNaN(copy.invalid.getTime())); // trueRegular expressions
Only source and flags are recorded for a RegExp. The copy is built from those two strings. One piece of state is lost: lastIndex, which global and sticky regexes use to remember where the last match ended. The copy always starts at lastIndex 0.
const re = /a/g;
re.test('aaa');
console.log(re.lastIndex); // 1
const copy = structuredClone(re);
console.log(copy.source, copy.flags); // 'a' 'g'
console.log(copy.lastIndex); // 0
console.log(copy === re); // falseIf you clone a /g or /y regex in the middle of iterating with exec, the copy will start matching from the beginning of the string again.
Binary data: ArrayBuffer, typed arrays and DataView
An ArrayBuffer is copied byte for byte into a new buffer. Typed arrays (Uint8Array, Float64Array, BigInt64Array and the rest) and DataView are views onto a buffer. The algorithm clones a view by cloning its underlying buffer and then creating a view of the same type, with the same byteOffset and length, over the new buffer.
This has a consequence that surprises many people. The algorithm copies the whole buffer, including bytes the view cannot see.
const whole = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8]);
const view = whole.subarray(2, 4); // sees [3, 4]
const copy = structuredClone(view);
console.log(copy); // Uint8Array(2) [ 3, 4 ]
console.log(copy.byteOffset); // 2
console.log(copy.buffer.byteLength); // 8, the entire original buffer
copy[0] = 99;
console.log(whole[2]); // 3, the original is untouchedWhen you take a small view of a large buffer, perhaps a 100-byte window into a 50 MB file, and clone that view, you also copy the full 50 MB. If you only want the visible bytes, copy them into a buffer of the right size first:
const whole = new Uint8Array(1024 * 1024);
const view = whole.subarray(0, 100);
const compact = structuredClone(view.slice()); // slice() makes a 100-byte buffer
console.log(compact.buffer.byteLength); // 100DataView follows the same rules:
const buffer = new ArrayBuffer(16);
const dv = new DataView(buffer, 4, 8);
dv.setFloat32(0, 1.5);
const copy = structuredClone(dv);
console.log(copy instanceof DataView); // true
console.log(copy.byteOffset, copy.byteLength); // 4 8
console.log(copy.getFloat32(0)); // 1.5Copying large buffers costs time and memory. The chapter "Moving Instead of Copying: The transfer Option" shows how to move a buffer's memory without copying it.
Map and Set
A Map is cloned by cloning every key and every value, then inserting them into a new Map in the original insertion order. Set works the same way with its members. This is the second big difference from JSON, which turns both into {}.
Because keys are cloned too, object keys in the copy are new objects. You cannot look up a cloned map with the key object you used on the original:
const key = { id: 1 };
const original = new Map([[key, 'one'], ['plain', { n: 2 }]]);
const copy = structuredClone(original);
console.log(copy.get('plain')); // { n: 2 }
console.log(copy.get(key)); // undefined
const [copiedKey] = copy.keys();
console.log(copiedKey); // { id: 1 }
console.log(copiedKey === key); // false
console.log(copy.get(copiedKey)); // 'one'String, number and other primitive keys keep working, because primitives are compared by value. If your code looks up map entries by object identity, that code will not work on a cloned map. You would need to rebuild the map with your own keys or switch to primitive keys such as ids.
WeakMap and WeakSet are not supported. Their contents cannot be listed, so there is nothing for the algorithm to walk.
Arrays and plain objects
Arrays and plain objects are the containers the algorithm walks. For both, it copies each own enumerable property whose key is a string. Each property value is cloned recursively by the same rules.
Arrays keep their length, their holes and any extra non-index properties:
const arr = [1, , 3];
arr.label = 'scores';
const copy = structuredClone(arr);
console.log(copy.length); // 3
console.log(1 in copy); // false, the hole is still a hole
console.log(copy.label); // 'scores'
console.log(Array.isArray(copy)); // truePlain objects keep their property order and their values. Inherited properties and non-enumerable properties are not copied:
const proto = { inherited: true };
const obj = Object.create(proto);
obj.visible = 1;
Object.defineProperty(obj, 'hidden', { value: 2, enumerable: false });
const copy = structuredClone(obj);
console.log(copy); // { visible: 1 }
console.log(copy.inherited); // undefined
console.log(Object.getPrototypeOf(copy) === Object.prototype); // trueThe copy always gets Object.prototype as its prototype. The chapter "Class Instances, Getters and Other Things That Do Not Survive" covers that loss in detail, along with getters and symbol keys.
Errors
The seven standard error constructors are supported. The algorithm reads the error's name. If the name is one of the standard ones, the copy gets that constructor's prototype. Any other name falls back to plain Error. The algorithm also copies message, and engines such as V8 and SpiderMonkey copy stack too. Other own properties are dropped.
const err = new RangeError('too big');
err.code = 'E_RANGE';
const copy = structuredClone(err);
console.log(copy instanceof RangeError); // true
console.log(copy.message); // 'too big'
console.log(copy.code); // undefined
class ValidationError extends Error {
constructor(message) {
super(message);
this.name = 'ValidationError';
}
}
const custom = structuredClone(new ValidationError('bad input'));
console.log(custom instanceof ValidationError); // false
console.log(custom instanceof Error); // true
console.log(custom.name); // 'Error'
console.log(custom.message); // 'bad input'This matters when errors cross a worker boundary. Custom error classes and fields like code or status do not survive the trip. If the receiving side needs them, send a plain object such as { name, message, code } and rebuild the error there.
Browser platform objects
In browsers, many Web API objects are marked as serializable. They include Blob, File, FileList, ImageData, ImageBitmap, CryptoKey, the geometry types (DOMPoint, DOMRect, DOMMatrix, DOMQuad) and RTCCertificate. Each one defines its own rule. A Blob clone, for example, refers to the same immutable bytes, and an ImageData clone copies its pixel data.
Support depends on the runtime. Node.js, Deno and Bun each implement only part of this list, so check before you rely on cloning a platform object outside the browser. DOM nodes such as HTMLElement are not serializable anywhere, and cloning one throws.
Common mistakes
| Mistake | What actually happens | Fix |
|---|---|---|
| Looking up a cloned `Map` with the original key object | Returns `undefined` because keys were cloned | Use primitive keys, or read keys from the copy |
| Cloning a small typed array view of a big buffer | The entire buffer is copied | Call `.slice()` first |
| Expecting a cloned `/g` regex to continue matching | `lastIndex` resets to 0 | Save and restore `lastIndex` yourself |
| Sending a custom error class through a clone | Becomes a plain `Error` without extra fields | Send a plain object and rebuild |
| Assuming JSON and structuredClone give the same result | structuredClone keeps `Date`, `Map`, `Set`, `undefined`, `NaN`, bigint | Use whichever matches the data you need to keep |
Exercise
You clone new Uint16Array(new ArrayBuffer(64), 8, 4). What are the copy's length, byteOffset and buffer.byteLength?
Show answer
length is 4, byteOffset is 8 and buffer.byteLength is 64. The algorithm copies the whole underlying buffer and rebuilds a view with the same offset and length.
Exercise
Given const k = { id: 7 }; const m = new Map([[k, 'x'], [7, 'y']]); const c = structuredClone(m);, what do c.get(k) and c.get(7) return, and why?
Show answer
c.get(k) returns undefined because the object key was cloned into a new object, so it no longer has the same identity as k. c.get(7) returns 'y' because primitive keys are compared by value.
Exercise
An object { when: new Date(NaN), ratio: -0, total: 5n, pattern: /x/gi } is cloned. Describe each property in the copy.
Show answer
when is a Date whose getTime() is NaN, so it is still an invalid date. ratio is -0, and Object.is(copy.ratio, -0) returns true. total is the bigint 5n. pattern is a new RegExp with source 'x', flags 'gi' and lastIndex 0.
Exercise
A worker throws Object.assign(new TypeError('bad'), { field: 'email' }) and the error is structured-cloned back to the main thread. What does the main thread receive?
Show answer
A TypeError instance with message 'bad' and usually a stack. The field property is dropped, because only the error type, the message and the stack are serialized.