DEV Community

Cover image for How the JavaScript engine works: execution context, call stack and the event loop
Ganesh Joshi
Ganesh Joshi

Posted on Edited on Originally published at ganeshjoshi.dev

How the JavaScript engine works: execution context, call stack and the event loop

This post was created with AI assistance and reviewed for accuracy before publishing.

Most JavaScript bugs that feel mysterious are not mysterious. A variable that is undefined when you were sure it had a value, a setTimeout of zero milliseconds that runs after a promise, a "Maximum call stack size exceeded" error from a function that looks fine: each one is the engine doing exactly what its rules say. The rules are just rarely shown in one place.

This post walks through those rules in the order the engine meets them. First, what an engine is and what it does to your source. Then the global execution context and how functions get their own. Then the call stack, the heap and the event loop, which together decide when your code runs. At the end there is a visualizer that lets you step through a script one move at a time, so you can watch all of it happen instead of taking my word for it.

What a JavaScript engine is

An engine is the program that reads JavaScript text and runs it. Chrome, Edge and Node.js use V8. Firefox uses SpiderMonkey. Safari and Bun use JavaScriptCore. They differ a lot inside, but they all implement the same language specification, so they agree on what your code means.

Two things are worth separating early, because people blur them:

  • The engine runs the language: variables, functions, objects, promises, the call stack.
  • The environment wraps the engine and adds things that are not part of the language: setTimeout, fetch, the DOM, console, file access. The browser is one environment. Node.js is another.

setTimeout is not in the JavaScript specification at all. The browser provides it, and then hands the engine a callback to run later. That split is the key to the event loop, which comes later in this post.

From source text to running code

When the engine receives your script it does not run the text directly. It turns it into something cheaper to execute, in stages. The details below describe V8, the most documented engine, and the other engines follow the same broad shape.

1. Parsing. A scanner splits the text into tokens (const, total, =, 42). A parser then arranges the tokens into an abstract syntax tree, a tree of nodes such as a variable declaration containing an identifier and a literal. A syntax error is found here, which is why a stray bracket stops the whole file before a single line runs. Engines also parse lazily: V8 only skims a function's body with a lighter preparser, which still catches syntax errors, and parses it fully when the function is first called, because most code on a page never runs.

2. Bytecode. The tree is compiled into bytecode, a compact instruction list for a simple virtual machine. V8's interpreter, Ignition, runs it. Starting here keeps start-up fast and memory low. Functions that run a few times get compiled quickly into plain machine code by a baseline compiler called Sparkplug.

3. Optimisation. While the bytecode runs, the engine watches which functions are hot, meaning called often, and which types they see. A function that has only ever added two small integers can be recompiled into machine code that assumes exactly that. V8's optimising compilers (Maglev, a fast mid tier, and TurboFan, the top tier) do this. If the assumption breaks, say the function is suddenly called with a string, the engine throws the optimised code away and falls back to a lower tier. This is called deoptimisation, and it is why code that keeps the same shapes and types tends to be faster.

4. Garbage collection. Objects live on the heap, and nobody frees them by hand. The collector finds objects that can no longer be reached from your running code and reclaims them. V8 splits the heap into a young and an old generation, because most objects die young, and collects the young one often and cheaply (a scavenge), leaving the full mark-and-compact pass over the whole heap for less often.

You can look at stage one yourself. Paste any script into the JavaScript AST explorer and it shows the syntax tree the parser builds, and selecting text in the editor highlights the matching node. It is a quick way to see that a + b * c is not a line of text to the engine but a tree with the multiplication nested below the addition.

The global execution context

Everything your code does happens inside an execution context: the record the engine keeps about the code that is running right now. It holds which variables exist, what this is, and which outer scope to look in when a name is not found locally.

When a script starts, the engine creates the global execution context first. It is created in two phases, and the split explains most of what people call hoisting.

Creation phase. Before running a single line, the engine scans the code and sets things up:

  • It creates the global object (window in a browser, globalThis in general) and sets this.
  • Function declarations are stored in full, so you can call them before the line where they are written.
  • Variables declared with var are registered and set to undefined.
  • Variables declared with let and const are registered but left uninitialised. They exist, but touching them is an error until the declaration line runs. That gap is called the temporal dead zone.

Execution phase. Now the engine runs the code line by line, assigning values as it goes.

Here is why that matters:

console.log(count); // undefined, not an error
var count = 5;

console.log(total); // ReferenceError: Cannot access 'total' before initialization
let total = 10;

sayHi(); // works, the whole function was stored in the creation phase
function sayHi() {
  console.log('hi');
}
Enter fullscreen mode Exit fullscreen mode

Nothing was "moved to the top". The engine had already registered count during creation, with the value undefined, and had registered total as unusable. "Hoisting" is just the visible effect of the creation phase.

Function execution contexts

Every time you call a function, the engine creates a function execution context for that call, with the same two phases. The creation phase registers the function's parameters, its own var, let, const and inner function declarations, and works out this. The execution phase then runs the body.

Each context also carries a reference to the context it was defined in. That reference is the scope chain. When your code uses a name, the engine looks in the current context, then in the one it was defined inside, then outward until it reaches the global context. If the name is nowhere, you get a ReferenceError.

Note the word defined. Lookup follows where the function was written, not where it was called from. That single rule is what makes closures work:

function makeCounter() {
  let count = 0;
  return function () {
    count += 1;
    return count;
  };
}

const next = makeCounter();
console.log(next()); // 1
console.log(next()); // 2
Enter fullscreen mode Exit fullscreen mode

When makeCounter returns, its context is finished, yet count is still alive. The inner function holds a reference to the scope it was defined in, so the engine keeps that scope on the heap for as long as the function can still be reached. That retained scope is the closure.

The call stack

The engine can do one thing at a time, and it needs to remember where to go back to when a function finishes. It does that with the call stack: a last-in, first-out list of execution contexts.

  • The global context is pushed first and stays at the bottom.
  • Calling a function pushes a new context on top.
  • When a function returns, its context is popped and the engine resumes in the one beneath.
  • The context on top is the code running right now.
function multiply(a, b) {
  return a * b;
}
function square(n) {
  return multiply(n, n);
}
function printSquare(n) {
  console.log(square(n));
}
printSquare(4);
Enter fullscreen mode Exit fullscreen mode

When printSquare(4) runs, the stack grows to four frames at its tallest: the global context, then printSquare, then square, then multiply. It then unwinds as each call returns, and console.log gets its own short-lived frame on the way down. The stack traces you see in error messages are a printout of this list at the moment something went wrong.

The stack has a fixed size. A function that calls itself with no way to stop keeps pushing frames until the engine runs out:

function forever() {
  forever();
}
forever(); // RangeError: Maximum call stack size exceeded
Enter fullscreen mode Exit fullscreen mode

The exact limit depends on the engine and the size of each frame, but it is in the thousands to tens of thousands of calls, not millions. When you see that error, the fix is almost always a missing base case, or a loop that should replace deep recursion.

Because there is exactly one stack, JavaScript is single-threaded: one piece of code runs at a time, and nothing can interrupt it. A long loop on the stack blocks everything, including clicks and painting, until it finishes.

The heap

The stack holds the what is running records. The heap holds the objects, arrays and functions those records point to. A variable that holds an object really holds a reference, a pointer into the heap. That is why assigning an object to a second variable does not copy it, and why a closure can keep an object alive after the function that made it has left the stack.

Primitive values such as numbers and booleans are small and are stored directly, while objects go to the heap and are reclaimed by the garbage collector once nothing can reach them.

Waiting without blocking: the event loop

If the engine can only run one thing at a time, how does a page fetch data or wait a second without freezing? It hands the waiting to the environment and carries on.

When you call setTimeout, the engine does not wait. It asks the browser to start a timer, which runs outside the JavaScript thread, in what is usually drawn as the Web APIs area. The engine finishes its current work. When the timer expires, the browser does not run your callback directly, because the stack might be busy. It places the callback in a queue.

The event loop is the rule that moves work from the queues to the stack. It runs forever, and each turn goes roughly like this:

  1. Run the current script or task until the call stack is empty.
  2. Drain the microtask queue: run every microtask, including any new ones added while draining, until it is empty.
  3. Let the browser render, if it needs to.
  4. Take the next task from the task queue and run it, then go back to step 2.

There are two queues, and the difference between them is the most important detail in this whole topic:

  • The task queue (also called the macrotask queue) holds things like timer callbacks, user events and message events. One task runs per turn of the loop.
  • The microtask queue holds promise reactions (.then, .catch, .finally, and the code after an await) and queueMicrotask callbacks. The whole queue is emptied after the current script or task, before the loop touches the next task or lets the browser paint.

So microtasks always jump ahead of tasks. Try to predict this before reading on:

console.log('start');

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

Promise.resolve().then(() => {
  console.log('promise');
});

console.log('end');
Enter fullscreen mode Exit fullscreen mode

The output is start, end, promise, timeout. Here is why:

  1. console.log('start') runs on the stack and prints immediately.
  2. setTimeout hands a zero-millisecond timer to the Web APIs. The timer expires almost at once, and its callback goes into the task queue.
  3. Promise.resolve().then(...) has an already-resolved promise, so its callback goes into the microtask queue.
  4. console.log('end') prints. The script is finished and the stack is empty.
  5. The loop drains the microtask queue first, so promise prints.
  6. Only then does the loop take the next task, so timeout prints.

The zero in setTimeout(fn, 0) does not mean "now". It means "as soon as the loop gets to the task queue and the stack is empty", and by then every microtask has already run. It is also a minimum. A busy stack makes the callback late, and browsers apply a minimum delay to timers that are nested deeply or running in background tabs.

async and await are promises underneath

An async function runs like a normal function until its first await. At that point it pauses, the rest of the function is scheduled as a microtask to continue once the awaited promise settles, and control returns to whoever called it.

async function a() {
  console.log('a1');
  await b();
  console.log('a2');
}
async function b() {
  console.log('b');
}

console.log('s');
a();
Promise.resolve().then(() => console.log('p'));
console.log('e');
Enter fullscreen mode Exit fullscreen mode

The output is s, a1, b, e, a2, p. Calling a() runs synchronously up to the await, so a1 and b print before e. The continuation a2 was queued as a microtask before the .then callback was queued, so it goes first. Once you see await as "queue the rest of this function as a microtask", the ordering stops looking random.

One note for Node.js: it has its own phases in the loop, and process.nextTick callbacks run even before promise microtasks. The core idea, that the stack empties, then microtasks drain, then the next task runs, is the same.

Watch it happen

Reading about queues is one thing. Seeing the stack grow and shrink while a timer counts down is much better for making it stick, so I built a tool for it: the JavaScript Event Loop and Call Stack Visualizer.

You paste a short script (or pick one of the examples), press Visualize, and then step through it with Next, Back and Play. At every step you can see:

  • The code, with the line that is about to run highlighted.
  • The call stack as a tower of blocks. The global context sits at the bottom, each call stacks on top, and the block on top is the code running now. Each block shows its variables, including let and const bindings that are still in the temporal dead zone, and whether the context is in its creation or execution phase.
  • The Web APIs area, where timers wait with a dial counting down.
  • The microtask queue and the task queue, with the job that runs next marked.
  • The event loop itself, showing whether it is running the script, draining microtasks, picking the next task or idle.
  • The console output, built up as the run progresses.

A good first run is the "Timeout vs promise" example from the post above. Step through it and watch the setTimeout callback sit in the task queue while the then callback runs first. Then try "Hoisting" to see var start as undefined and let start as "not initialised", and "async / await" to see the continuation land in the microtask queue. Then change the code and predict the output before you press Next.

Two things about how it works, so you know what you are looking at:

  • Your code is never passed to eval or Function. The tool includes a small interpreter for plain scripts, written to record every step, so it can show internals a real engine does not expose. It runs entirely in your browser, and nothing you type is sent anywhere.
  • It is a model, not V8. Timers use a virtual clock, so a 1000 ms timer does not make you wait a second. It handles the core of the language, including functions, closures, var, let, const, promises, async and await, and timers. It does not support classes, imports or regular expressions, and a run is capped at a limited number of steps so that an infinite loop stops instead of hanging the page. For the behaviours in this post, the order things run in is what matters, and that is what it shows.

A short checklist

  • The engine parses your code into a tree, compiles it to bytecode, and optimises the hot paths while it runs.
  • A global execution context is created first, in two phases. Creation registers names (var as undefined, let and const as unusable until their line, functions in full). Execution runs the lines.
  • Every call creates a function execution context and pushes it on the call stack. Name lookup follows the scope chain, which follows where a function was defined.
  • A closure is a function plus the scope it was defined in, kept alive on the heap.
  • There is one stack, so one thing runs at a time. Waiting is handed to the environment, and finished work comes back through queues.
  • After the stack empties, the event loop drains the microtask queue completely, then runs one task from the task queue, and repeats.
  • Promise reactions and the code after await are microtasks. Timers are tasks. That is why promise prints before timeout.

If you want to go further, the JavaScript AST explorer shows what the parser makes of your code, and the event loop visualizer shows what the engine does with it next. Use them together and the path from a line of text to a running program stops being a black box.

Top comments (0)