What is JavaScript's event loop? How a single thread handles async work
Before getting into the Event Loop, I'll start with Single Thread, one of JavaScript's characteristics.
Thread & Process
- Process: The running program itself. The operating system manages it as one independent unit of work. Each process has its own memory space and runs independently.
- Thread: A small unit of work that runs inside a process. One process can have several threads, and the threads share memory space within the same process and can run at the same time.
Single Thread & Multi Thread
- Single thread: All work is handled on one thread. In other words, only one task can be handled at a time.
- Multi thread: Several threads run at the same time, so one process can handle several tasks at once.
Why is JavaScript single-threaded?
JavaScript was designed to be single-threaded by default. When JavaScript was first used in web browsers, it was made to finish one task before handling the next, so that DOM manipulation would be handled safely. If several threads manipulated the DOM at the same time, data conflicts could occur.
How JavaScript runs

The JavaScript engine is made up of two main parts, the Memory Heap and the Call Stack.
- Memory Heap : where memory allocation happens
- Call Stack : where code piles up one call at a time, in the form of a stack, as it runs
Memory Heap & Call Stack
First, the code the user wrote, held in the Memory Heap, gets piled onto the Call Stack in Stack order and runs. At this point, synchronous functions run as they are, while asynchronous functions are handed to the Web API, which splits up the work.
- Stack : last in, first out (LIFO), where the last item in is the first to leave
Web API
Many of the APIs we use often with JavaScript are not actually provided by JavaScript but by the web browser. Examples include DOM, AJAX, and Timeout.
An asynchronous function run on the Call Stack is handled by the Web API, and meanwhile the Call Stack handles the remaining synchronous functions.
The Web API processes the asynchronous functions and passes the ones that have finished to the Callback Queue.
Event Loop
The Event Loop keeps watching the state of the Call Stack and the Callback Queue, and when there are no functions on the Call Stack, it pushes the asynchronous functions in the Callback Queue onto the Call Stack.
Then the Call Stack runs the asynchronous function.
Why JavaScript is single-threaded yet can behave as if it were multi-threaded
As explained above, JavaScript is single-threaded by default, but it can process asynchronous work in parallel because it uses systems that run on multiple threads in environments like the browser or Node.js.
- #event loop
- #JavaScript
- #Single Thread
- #web API
- #call stack
- #callback queue