Course contentsShow
← JavaScript
Lesson 2006 of 2,72341. Modern JavaScript Features (ES2020+)Free lesson

Transfer and Detaching with structuredClone

Using the transfer option to move ArrayBuffers and other transferables instead of copying them.

Transfer and Detaching with structuredClone

You'll learn how to use the transfer option in structuredClone to move data ownership instead of copying, making certain operations dramatically more efficient.

The Core Idea

When you clone an ArrayBuffer or other transferable objects, structuredClone normally creates a copy—two separate chunks of memory holding the same data. But sometimes you don't need the original anymore. The transfer option lets you move ownership of the data rather than duplicating it, making the original unusable (detached) in the process.

Think of it like moving house: copying means hiring movers to duplicate everything (expensive), while transferring means just handing over the keys to your existing furniture (instant and free).

Using the Transfer Option

const buffer = new ArrayBuffer(1024);
const view = new Uint8Array(buffer);
view[0] = 42;

// Transfer the buffer instead of copying
const cloned = structuredClone(
  { data: buffer },
  { transfer: [buffer] }
);

console.log(cloned.data.byteLength); // 1024
console.log(buffer.byteLength);      // 0 - detached!

After transferring, the original buffer is detached—it has zero length and cannot be used. The cloned object now owns that memory exclusively.

Why This Matters

Transferring is crucial for performance when dealing with large binary data, like video frames, audio buffers, or file contents. Instead of copying megabytes of data, you instantly hand off ownership, saving both time and memory.

What Can Be Transferred

Only certain objects support transfer: ArrayBuffer, MessagePort, ImageBitmap, and a few others. Regular objects, strings, and numbers cannot be transferred—they're always copied.

Key Takeaway: Use structuredClone's transfer option to move ownership of ArrayBuffer and other transferables, detaching the original and avoiding expensive memory copies for large binary data.