← Back to JavaScript, page 4

javascript-0074 · Medium mid

What is the structured clone algorithm, which values can it copy, and what does transferring an ArrayBuffer do?

The structured clone algorithm is the built-in way to deep copy values. structuredClone and postMessage both use it. It handles many types that JSON cannot, such as Date, Map, Set, typed arrays, and cycles, but it fails for functions and DOM nodes and drops prototypes. Transferring an ArrayBuffer moves its memory to the new owner without copying and leaves the original empty.

Full answer

Structured cloning is how browsers copy data between realms: into a Web Worker with postMessage, into IndexedDB, and through structuredClone(value) in your own code. The algorithm walks the value, copies it, and remembers objects it has seen so that cycles and shared references stay intact.

It supports primitives (except symbols), Boolean, String, and Number wrapper objects, Date, RegExp, Map, Set, ArrayBuffer and typed arrays, BigInt, Error objects (with their name and message), arrays, and plain objects. It does not support functions (a DataCloneError), DOM nodes, and symbols as values. For class instances, only own enumerable data properties are copied and the prototype is lost, so methods disappear. Getters are called and their results are copied as plain values. Property descriptors and non-enumerable properties are not preserved.

Cloned data is fully separate from the original. A Map keyed by objects keeps the relationship between its cloned keys, and two references to the same object in the input still point to one cloned object in the output.

Transferring is an option for big binary data. When an ArrayBuffer is listed in the transfer option, its memory moves to the new owner, no bytes are copied, and the original buffer becomes detached with a byteLength of 0. It is the fast way to hand a large image or audio buffer to a worker. A SharedArrayBuffer is not transferred but shared, which is a different feature.

Because a clone is a snapshot, later changes on either side are not visible to the other.

javascript
const original = {
  created: new Date('2026-04-01T00:00:00Z'),
  pattern: /ab+c/gi,
  tags: new Set(['js']),
  scores: new Map([[{ id: 1 }, 90]]),
  big: 12345678901234567890n,
  bytes: new Uint8Array([1, 2, 3]),
};
original.self = original;

const copy = structuredClone(original);
console.log(copy.created instanceof Date, copy.pattern.flags, copy.tags.has('js'), copy.big);
console.log(copy.self === copy, copy.self !== original, copy.bytes !== original.bytes);

const shared = { value: 1 };
const twoRefs = structuredClone({ a: shared, b: shared });
console.log(twoRefs.a === twoRefs.b);

class Student {
  constructor(name) {
    this.name = name;
  }
  get upper() {
    return this.name.toUpperCase();
  }
  hello() {
    return 'hi';
  }
}
const student = structuredClone(new Student('Asha'));
console.log(student instanceof Student, typeof student.hello, student.name);

const withGetter = structuredClone({ get computed() { return 42; } });
console.log(Object.getOwnPropertyDescriptor(withGetter, 'computed'));

for (const [label, value] of [['function', { fn() {} }], ['symbol', Symbol('s')]]) {
  try {
    structuredClone(value);
  } catch (error) {
    console.log(label, '->', error.name);
  }
}
console.log(structuredClone(new Error('failed')).message);

const buffer = new ArrayBuffer(8);
const moved = structuredClone(buffer, { transfer: [buffer] });
console.log('original:', buffer.byteLength, buffer.detached, 'moved:', moved.byteLength);

const { port1, port2 } = new MessageChannel();
const data = new Uint8Array(4).buffer;
port2.onmessage = (event) => {
  console.log('received', event.data.byteLength, 'sender sees', data.byteLength);
  port1.close();
};
port1.postMessage(data, [data]);

Run with Node.js v24.22.1 as js-74.js; two runs gave identical output. Output: true gi true 12345678901234567890n true true true true false undefined Asha { value: 42, writable: true, enumerable: true, configurable: true } function -> DataCloneError symbol -> DataCloneError failed original: 0 true moved: 8 received 4 sender sees 0

Key points

  • structuredClone and postMessage use the same algorithm.
  • Supports Date, RegExp, Map, Set, typed arrays, BigInt, Error, and cycles; not functions or DOM nodes.
  • Class instances lose their prototype; getters become plain values.
  • Shared references and cycles are preserved in the copy.
  • Transfer moves an ArrayBuffer without copying and detaches the original.

Common mistakes

  • Expecting class instances to keep their methods after cloning.
  • Passing functions or DOM nodes and getting a DataCloneError.
  • Using a transferred buffer after the transfer and finding it empty.
  • Assuming cloning keeps getters as getters.

Follow-ups

  • How is a SharedArrayBuffer different from a transferred ArrayBuffer?
  • Which types does JSON handle that structuredClone does not, and the reverse?
  • How would you copy a class instance and keep its prototype?

Tips

  • Name the supported types that JSON lacks: Date, Map, Set, cycles, and typed arrays.
  • State the prototype loss for class instances; it is the common surprise.
  • Explain transfer as a move with no copy, and mention that the sender loses access.