Sub topic 2
The Call Stack
This chapter assumes you can write JavaScript functions and closures, pass callbacks, and run code in a browser console or Node.js. The previous chapter showed that JavaScript runs one piece of code at a time on a single thread. This chapter covers the structure that tracks which code is running: the call stack.
What the Call Stack Is
The call stack is a data structure the engine uses to keep track of function calls that have started but not yet returned. It works last in, first out. The most recently called function sits on top, and it must finish before anything below it can continue.
Each entry on the stack is a stack frame (also called an execution context). A frame holds:
- The function being run and the current position inside it.
- Its local variables and arguments.
- A reference to its outer scope, which is how closures find their variables.
- The place to return to when the function finishes.
The engine follows two rules:
- Calling a function pushes a new frame onto the top of the stack.
- Returning from a function (or throwing out of it) pops that frame off.
When a script starts, the engine pushes a frame for the top-level code, often shown as (anonymous) or <global> in debuggers. When the script's last line finishes, that frame is popped and the stack is empty.
Watching Frames Push and Pop
Here is a small program with three nested calls:
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: 16Here is what the stack looks like at each step:
| Step | What happens | Stack (top first) |
|---|---|---|
| 1 | Script starts | global |
| 2 | `printSquare(4)` is called | printSquare, global |
| 3 | `square(4)` is called | square, printSquare, global |
| 4 | `multiply(4, 4)` is called | multiply, square, printSquare, global |
| 5 | `multiply` returns 16 | square, printSquare, global |
| 6 | `square` returns 16 | printSquare, global |
| 7 | `console.log(16)` is called | console.log, printSquare, global |
| 8 | `console.log` returns | printSquare, global |
| 9 | `printSquare` returns | global |
| 10 | Script ends | (empty) |
At any moment only the top frame is executing. The frames below it are paused partway through and waiting for the call above them to return. This is the run-to-completion idea from the previous chapter, seen at the level of individual function calls.
Reading the Stack: Stack Traces
Each time you see a stack trace, you are looking at a snapshot of the call stack. When an error is created, the engine records the frames that are on the stack at that moment.
function multiply(a, b) {
console.log(new Error('snapshot').stack);
return a * b;
}
function square(n) {
return multiply(n, n);
}
function printSquare(n) {
console.log(square(n));
}
printSquare(4);In Node.js the output looks roughly like this (file paths and line numbers vary):
Error: snapshot
at multiply (/path/to/file.js:2:15)
at square (/path/to/file.js:7:10)
at printSquare (/path/to/file.js:11:15)
at Object.<anonymous> (/path/to/file.js:14:1)
...
16The top line of the trace is the top of the stack. Read downward to see who called whom. console.trace() prints the same information without creating an error. In browser DevTools, pausing at a breakpoint shows the same list in the Call Stack panel. You can click any frame there to inspect its local variables.
Stack Overflow
The stack has a limited size. The limit depends on the engine and on how large each frame is, and it is typically somewhere in the thousands to tens of thousands of frames. If calls keep pushing frames without returning, the engine runs out of room and throws an error:
let depth = 0;
function recurse() {
depth++;
recurse();
}
try {
recurse();
} catch (e) {
console.log(e.name); // "RangeError" in V8 and JavaScriptCore
console.log(e.message); // "Maximum call stack size exceeded"
console.log('depth reached:', depth);
}Firefox reports the same situation as InternalError: too much recursion. In every engine the error is thrown inside the deepest frame and travels down through the frames as they pop, so the catch at the bottom can handle it.
The usual causes are:
- A recursive function with a missing or unreachable base case.
- Two functions that call each other without end, such as a setter that assigns to its own property.
- Recursion that is correct but too deep for the input, such as walking a linked list of 100,000 nodes.
The ES2015 specification defines proper tail calls, but in practice only Safari's JavaScriptCore implements them. Don't rely on tail-call elimination. For deep inputs, rewrite the recursion as a loop:
// Recursive: overflows for very large arrays
function sumRecursive(arr, i = 0) {
if (i === arr.length) return 0;
return arr[i] + sumRecursive(arr, i + 1);
}
// Iterative: uses one frame no matter how large the input
function sumIterative(arr) {
let total = 0;
for (let i = 0; i < arr.length; i++) {
total += arr[i];
}
return total;
}
const big = Array.from({ length: 200000 }, () => 1);
console.log(sumIterative(big)); // 200000
try {
console.log(sumRecursive(big));
} catch (e) {
console.log('recursive version failed:', e.message);
}The Stack and Asynchronous Callbacks
This section matters for the rest of the tutorial. A callback passed to setTimeout, an event listener, or .then() is not called by the function that registered it. It runs later, on a stack that is empty apart from its own frame, after the code that registered it has already returned.
That has two practical effects.
try/catch does not reach across the gap
function schedule() {
try {
setTimeout(() => {
throw new Error('boom');
}, 0);
} catch (e) {
console.log('caught:', e.message); // never runs
}
}
schedule();
console.log('schedule returned');
// Output: "schedule returned", then an uncaught Error: boom
// (in Node.js this uncaught error ends the process)By the time the callback throws, schedule and its try block have already been popped off the stack. Nothing below the callback's frame can catch the error. To handle the error, put the try/catch inside the callback, or use promises and await, which carry rejections forward explicitly.
Stack traces lose their history
Because the original caller's frames are gone, a plain stack trace from inside a callback only shows the frames from the current run. Modern DevTools and Node.js partly work around this with async stack traces. These stitch in the frames from the point where the callback was scheduled, marked with a separator such as await or setTimeout (async). This is a debugging aid that the engine records on the side. The real call stack still contains only the current run's frames.
Common Misconceptions
| Misconception | What actually happens |
|---|---|
| "`setTimeout` pauses my function until the timer fires." | `setTimeout` pushes a frame, hands the timer to the host, and returns at once. Your function keeps running. |
| "A callback runs inside the function that registered it." | It runs later in its own frame, after the registering function has returned. |
| "Recursion is fine because the stack is large." | The limit is engine-specific and can be only around ten thousand frames. Input size decides whether you overflow. |
| "Async stack traces mean the old frames are still there." | They are reconstructed for debugging. The real stack holds only the current run's frames. |
Summary
- The call stack is a last-in, first-out list of frames for functions that have started but not returned.
- Calling a function pushes a frame. Returning or throwing pops it. Only the top frame runs.
- Stack traces and the DevTools Call Stack panel show the stack at one moment.
- Unbounded or very deep recursion exhausts the stack and throws a
RangeError(in Firefox, anInternalError). - Asynchronous callbacks start on an empty stack, so
try/catchin the registering function cannot catch their errors.
The next chapter looks at where the timer actually waits while your code keeps running: the host APIs.
Exercise
List the call stack, top first, at the moment "inner" is logged, and say what is on the stack when "later" is logged. function outer() { middle(); } function middle() { setTimeout(function later() { console.log('later'); }, 0); inner(); } function inner() { console.log('inner'); } outer();
Show answer
When "inner" is logged, the stack is console.log, inner, middle, outer, global. When "later" is logged, outer, middle, and the global script frame have all returned, so the stack holds only console.log on top of later. The later callback was scheduled by middle but not called by it.
Exercise
A function walks a tree recursively and throws "Maximum call stack size exceeded" only for very deep trees. Name two ways to fix it without depending on tail-call optimization.
Show answer
Rewrite the traversal as a loop that keeps its own explicit stack, for example an array you push nodes onto and pop them from. Or limit the depth and split the work across separate calls so the stack unwinds in between. The explicit-stack loop is the usual fix because it keeps the work in a single frame, and an array can grow far larger than the call stack.
Exercise
Why does wrapping setTimeout(() => { throw new Error('x'); }, 0) in try/catch fail to catch the error, and where should the try/catch go instead?
Show answer
The try block's frame is popped as soon as setTimeout returns. The callback runs later on an otherwise empty stack, so no enclosing catch frame is left below it. Put the try/catch inside the callback itself, or wrap the delay in a promise and await it inside a try block.