Structured Clone for Message Passing
What you'll learn: How data is safely copied—not shared—when sent between worker threads using the structured clone algorithm.
When you send data between a main thread and a worker (or between workers), JavaScript doesn't pass a reference to the original object. Instead, it creates a deep copy using the structured clone algorithm. This means the receiving thread gets its own independent version of the data, with no shared memory.
Why Cloning, Not Sharing?
Imagine two people working on separate whiteboards. If you want to share information, you can't hand them your whiteboard—you write a copy on theirs. That's structured cloning: each thread has its own isolated memory space, so JavaScript copies the data when you call postMessage().
What the Algorithm Handles
Structured clone can copy:
- Primitives (numbers, strings, booleans)
- Objects and arrays (nested deeply)
- Dates, RegExp, Maps, Sets
- ArrayBuffers, TypedArrays
- Blobs, ImageData
It cannot copy:
- Functions
- DOM nodes
- Symbols
- Prototypes (objects become plain)
The Cost of Cloning
Copying large objects takes time and memory. For a 10 MB array, structured clone must serialize it in one thread and deserialize in the other—potentially doubling memory usage temporarily.
// Main thread
const largeArray = new Array(1_000_000).fill({id: 1, data: "example"});
worker.postMessage({payload: largeArray}); // Full deep copy happens here
The worker receives a new array, completely independent of the original. Changes in the worker won't affect the main thread's data.
Key Takeaway: Data passed via postMessage() is deeply cloned using structured clone—you get isolation and safety, but at the cost of time and memory for large payloads.