The Call Stack & Event Loop

Understanding how JavaScript manages execution is key to mastering asynchronous behavior and performance. Two core concepts help explain this: the Call Stack and the Event Loop.

The Call Stack

The call stack is a data structure that keeps track of function calls in your code. It follows a Last In, First Out (LIFO) principle:

  • When a function is called, it’s added (pushed) onto the stack.
  • When a function returns, it’s removed (popped) from the stack.

This means only one function executes at a time, making JavaScript single-threaded.

Illustration of call_stack_event_loop
Illustration of call_stack_event_loop

💡 Call Stack Key Point

If a function calls another function, the new function is pushed on top, and the previous one waits until the new one finishes.

Example of Call Stack Behavior

📌 Deep Dive: Simple Function Calls

JAVASCRIPT
function first() {
  second();
  console.log('First done');
}

function second() {
  console.log('Second done');
}

first();
Output
Second done First done

The Event Loop

JavaScript executes synchronously but supports asynchronous operations via the event loop. The event loop enables non-blocking behavior by managing the execution of asynchronous callbacks.

Here’s how it works in brief:

  • The call stack runs functions synchronously.
  • Asynchronous events (like timers, HTTP requests) place their callbacks into the callback queue once ready.
  • The event loop constantly checks if the call stack is empty.
  • When the stack is empty, the event loop pushes the next callback from the queue onto the call stack for execution.

💡 Event Loop Insight

Even if an asynchronous callback is ready, it waits in the queue until the call stack is empty.

Call Stack vs. Callback Queue
Call StackCallback Queue
Synchronous function callsAsynchronous callbacks waiting to run
Executes one function at a timeHolds callbacks until the stack is free
Last In, First Out (LIFO)First In, First Out (FIFO)

Example: setTimeout and the Event Loop

📌 Deep Dive: Asynchronous Callback Execution

JAVASCRIPT
console.log('Start');

setTimeout(() => {
  console.log('Timeout callback');
}, 0);

console.log('End');
Output
Start End Timeout callback

Even with a zero delay, the setTimeout callback runs after all synchronous code because it goes to the callback queue first.

⚠️ Common Misconception

setTimeout with 0ms delay does NOT run immediately after the delay but waits until the current call stack is empty.

Summary

  • Call Stack: Manages synchronous function execution, one at a time.
  • Event Loop: Bridges asynchronous events by moving ready callbacks from the queue to the stack.
  • This model allows JavaScript to handle asynchronous code without blocking.