Sub topic 1
How JavaScript Runs Code in Parallel
JavaScript is often called single-threaded. That is true for any one piece of running code, but modern JavaScript hosts can run many pieces of code at the same time. This chapter explains how browsers and Node.js do that, what each thread owns, and how threads talk to each other by default. Everything in the rest of this tutorial builds on this model. Shared memory changes one specific rule here, and you need to know the rule before you break it.
Prerequisites
This chapter assumes you already know:
- Modern JavaScript syntax (ES2015+):
const, arrow functions, classes, modules. ArrayBufferand typed arrays such asInt32Array.- The event loop, and asynchronous code with Promises and
setTimeout. - How to start a Web Worker or a Node.js
worker_threadsWorker and send it a message. - What an HTTP response header is. Later chapters need this; this one does not.
The code samples run in Node.js 18 or newer. The ideas apply to browsers too.
The Agent: JavaScript's Unit of Execution
The ECMAScript specification does not talk about "threads". It talks about agents. An agent is an independent JavaScript execution context. Each agent has:
- Its own heap of objects. One agent cannot hold a reference to an object in another agent's heap.
- Its own execution stack.
- Its own job queue and event loop.
In a browser, the main window is one agent. Each dedicated Web Worker is another. In Node.js, the main thread is one agent and each Worker from node:worker_threads is another. The host maps agents onto operating system threads, so two agents really can run at the same instant on two CPU cores.
Inside one agent, the old rule still holds: code runs to completion. When a function starts, nothing else in that agent runs until the current task finishes. No callback, timer, or promise reaction can interrupt it.
const start = Date.now();
setTimeout(() => {
console.log(`timer fired after ${Date.now() - start} ms`);
}, 0);
// Busy loop for 500 ms. The timer cannot run until this task ends.
while (Date.now() - start < 500) {}
console.log('loop finished');
// Output:
// loop finished
// timer fired after 500 ms (approximately)The timer asked for a 0 ms delay, but it waited about 500 ms. The busy loop owned the agent the whole time. This guarantee is why ordinary JavaScript has no data races. Within one agent, two pieces of code never touch the same variable at the same time.
Agent Clusters
Agents that are allowed to share memory form an agent cluster. In a browser, a page and the dedicated workers it creates usually belong to one cluster. Pages from unrelated sites live in different clusters, and the browser may even put them in different processes. In Node.js, the main thread and all its worker threads form one cluster.
Being in the same cluster does not mean the agents share their heaps. It means they can share specific blocks of raw memory if you set that up on purpose. Without that step, every agent is isolated.
Message Passing: The Default Way Agents Communicate
Since agents cannot see each other's objects, they communicate by sending messages. postMessage puts a message on the receiving agent's queue. The receiver handles it later as a normal event, inside its own run-to-completion task.
The key detail is what happens to the data. By default, postMessage runs the structured clone algorithm. It walks the value and builds a deep copy in the receiver's heap. The sender keeps its original, and the receiver gets an independent copy.
This program shows the copy. The worker changes the array it receives, and the main thread's array does not change.
const { Worker } = require('node:worker_threads');
const workerCode = `
const { parentPort } = require('node:worker_threads');
parentPort.on('message', (numbers) => {
numbers[0] = 99;
parentPort.postMessage(Array.from(numbers));
});
`;
const worker = new Worker(workerCode, { eval: true });
const numbers = new Int32Array([1, 2, 3]);
worker.on('message', (workerView) => {
console.log('worker sees:', workerView); // [ 99, 2, 3 ]
console.log('main sees: ', Array.from(numbers)); // [ 1, 2, 3 ]
worker.terminate();
});
worker.postMessage(numbers);Copying is safe and simple, but it costs time and memory in proportion to the data size. Sending a 200 MB image buffer copies 200 MB on every message.
Transferring Instead of Copying
For ArrayBuffer and some other types, you can transfer ownership instead of copying. You list the buffer in a transfer list. The memory moves to the receiver, and the sender's buffer becomes detached: its length drops to 0 and it can no longer be used.
structuredClone uses the same algorithm as postMessage, so you can see the effect without a worker:
const buffer = new ArrayBuffer(1024);
console.log(buffer.byteLength); // 1024
const moved = structuredClone(buffer, { transfer: [buffer] });
console.log(moved.byteLength); // 1024
console.log(buffer.byteLength); // 0, the original is detachedWith a worker, you write worker.postMessage(buffer, [buffer]). Transfer is fast because no bytes are copied. But only one agent owns the memory at a time. Transfer hands the data over; it does not share it.
Comparing the Options
| Method | What the receiver gets | Sender can still use data? | Cost | Race risk |
|---|---|---|---|---|
| Structured clone (default) | An independent copy | Yes | Grows with data size | None |
| Transfer list | The same memory, moved | No, buffer is detached | Near zero | None |
| Shared memory (next chapter) | The same memory, at the same time | Yes | Near zero | Yes, needs Atomics |
The last row is the subject of this tutorial. A SharedArrayBuffer lets two agents use the same bytes at the same time. That removes the copy and keeps both sides working, but it also removes the isolation that made the first two rows race-free.
Why Message Passing Has No Races
The message-passing model is safe because of two facts working together:
- Each agent only ever touches its own heap.
- Messages are handled as whole tasks that run to completion.
So no two agents ever read or write the same variable. Coordination happens through the order of messages. The cost is latency: a message waits in a queue until the receiver's current task finishes. If the worker is in a long loop, it does not see your message until the loop ends.
Common Misconceptions
- "Workers share global variables with the page." They do not. A worker has its own
globalThis. SettingglobalThis.xin a worker has no effect on the main thread. - "
asynccode runs in parallel." Promises andasyncfunctions interleave tasks on one agent. They never run two pieces of JavaScript at once. Only multiple agents give true parallelism. - "Sending an object to a worker passes a reference." It passes a copy, or moves a transferable buffer. Functions, DOM nodes, and class prototypes cannot be cloned at all, and trying to send a function throws a
DataCloneError. - "Transferring keeps a copy on the sender." Transfer detaches the sender's buffer. Code that reads it afterward sees a length of 0.
Summary
Each agent runs its own code to completion with its own heap and event loop. Agents in a cluster run in parallel and, by default, exchange data only by copying or transferring it through messages. This isolation prevents data races but costs copying time or exclusive ownership. The next chapter introduces SharedArrayBuffer, which keeps both agents working on the same bytes at once.
Exercise
A main thread runs worker.postMessage(buf, [buf]) with a 4096-byte ArrayBuffer, then logs buf.byteLength. What is printed, and why?
Show answer
It prints 0. Listing buf in the transfer list moves its memory to the worker and detaches the sender's buffer, so the main thread's buf has a length of 0 and can no longer be used.
Exercise
A worker is running a synchronous loop that lasts 2 seconds. The main thread sends it a message 100 ms into that loop. When does the worker's message handler run?
Show answer
About 2 seconds after the loop started, once the loop's task completes. Each agent runs a task to completion, so the message sits in the worker's queue until its event loop is free.
Exercise
Two async functions on the main thread both increment the same global counter 1000 times with counter++, using await between increments. Can they produce a lost update the way two parallel threads might? Explain.
Show answer
No. Both functions run on the same agent, and each counter++ executes inside one task that runs to completion. The functions interleave between awaits but never execute at the same instant, so each increment reads and writes the counter without interruption. The final value is 2000.