Sub topic 2
The Call Stack
This chapter assumes you can write and call JavaScript functions, understand closures, and run code in a browser console or with Node.js. It builds on the previous chapter's idea that the engine runs one piece of code at a time, to completion.
What the Call Stack Is
The call stack is the structure the JavaScript engine uses to track which function is running right now and where to return when it finishes. Each function call pushes a stack frame onto the stack. A frame holds that call's arguments, local variables, and the point in the caller to resume. When the function returns, its frame is popped off and execution continues in the frame below.
The stack works last in, first out. Only the frame on top is running. Every frame beneath it is paused, waiting for the functions above it to return.
Watching Frames Push and Pop
function multiply(a, b) {
return a * b;
}
function square(n) {
return multiply(n, n);
}
function printSquare(n) {
const result = square(n);
console.log(result);
}
printSquare(4);
// Output: 16The engine first runs the top-level script in a global frame. Then the frames change like this:
printSquare(4)is pushed.square(4)is pushed on top of it.multiply(4, 4)is pushed, returns16, and is popped.squarereturns16and is popped.console.log(16)is pushed, prints, and is popped.printSquarereturns and is popped. The stack is back to the global frame.
Seeing the Stack Yourself
Error stack traces are snapshots of the call stack. You can print one without throwing:
function inner() {
console.trace('current stack');
}
function outer() {
inner();
}
outer();The trace lists inner first, then outer, then the top-level script. That is the stack from top to bottom. Debuggers show the same list in their "Call Stack" panel when you pause at a breakpoint.
Stack Overflow
The stack has a limited size. A recursion that never stops keeps pushing frames until the engine refuses to push another one:
function forever() {
return forever();
}
try {
forever();
} catch (err) {
console.log(err instanceof RangeError, err.message);
}
// Output (V8): true Maximum call stack size exceededThe exact limit depends on the engine and on frame size, often around ten thousand frames. Do not write code that relies on a particular depth.
Why the Stack Matters for the Event Loop
The stack must be completely empty before the engine can start any callback that was scheduled for later. While a frame is on the stack, nothing else runs. A slow function blocks everything behind it, including clicks, timers, and promise callbacks.
Common mistakes at this stage:
| Mistake | Reality |
|---|---|
| A callback passed to `setTimeout` runs "inside" the function that scheduled it | It runs later, on a fresh stack, after the scheduling function has returned |
| `try/catch` around `setTimeout` catches errors thrown in its callback | The callback runs in a different stack, so that `try` frame no longer exists |
| Deep recursion is fine because memory is large | Stack space is much smaller than heap space |
Exercise
In the printSquare example, what is the maximum number of frames on the stack at once, counting the global frame, and which function is on top at that moment?
Show answer
Four frames: global, printSquare, square, and multiply. multiply is on top. When console.log runs, the stack is only three deep (global, printSquare, console.log) because square and multiply have already been popped.
Exercise
Why does a try/catch around setTimeout(() => { throw new Error('x'); }, 0) fail to catch the error?
Show answer
The try block's frame is popped as soon as setTimeout returns. The callback runs later on a new call stack, so no enclosing try is active when the error is thrown.