Skip to main content
TOPIC 2 OF 8 · 2 MIN READ

The JavaScript Concurrency Model

The JavaScript concurrency model consists of several key components that work together to enable asynchronous execution: the Call Stack, Web APIs, Callback Queue, and Event Loop.

Key concepts

Call Stack

Executes functions in a last in, first out (LIFO) manner. Synchronous code is pushed and popped directly on the call stack. Asynchronous tasks are deferred to Web APIs or other threads.

Example
function greet() {
  console.log('Hello!');
}
greet(); // "Hello!" is executed immediately.

Web APIs

Provided by the browser or Node.js, handle asynchronous tasks like setTimeout, fetch, and DOM events. When a task completes, its callback is pushed into the callback queue.

Callback Queue

Holds completed asynchronous tasks. Tasks are moved to the call stack when it is empty.

Event Loop

Continuously checks if the call stack is empty. If the call stack is empty, the event loop moves the next task from the callback queue to the call stack for execution. The event loop is a mechanism in JavaScript that continuously monitors the call stack and the callback/microtask queues. It ensures that tasks from the callback queue (macrotasks) or microtask queue are pushed onto the call stack when it is empty, enabling non-blocking asynchronous execution.

Step by step

Execution Flow:

  • Synchronous code executes directly on the call stack.
  • Asynchronous tasks are sent to Web APIs.
  • When Web API tasks complete, callbacks go to the callback queue.
  • Event loop moves callbacks from queue to call stack when stack is empty.

Stuck on this one? Talk to Sumit.

Keys: F focus mode · ← → previous / next topic · Esc leave focus