Advanced · 1 of 11 · 15 min read
The call stack
How the engine tracks what is running, what a stack trace is really telling you, and why it overflows.
- Call stack
JavaScript has one thread, so at any instant exactly one function is executing. The call stack is how the engine remembers which function that is and where to return afterwards.
Push and pop
function third() {
return 'done';
}
function second() {
return third();
}
function first() {
return second();
}
console.log(first()); // "done"
What the stack holds over time:
first() → [first]
second() → [first, second]
third() → [first, second, third]
returns → [first, second]
returns → [first]
returns → []
11 The script is running. console.log(first()) has nothing to log yet, so it calls first.
11 first() is called and a frame goes on top, holding its arguments, its locals and where to resume.
8 first runs return second() — it has no value yet, so its frame cannot leave.
5 And again. Four frames are alive and three of them are doing nothing but waiting for the one above.
2 third returns 'done'. The first real value of the whole program appears, at the deepest point.
5 third's frame pops and the value is handed down. second had nothing else to do, so it is next.
8 Same again. The stack unwinds in exactly the reverse of the order it was built — last in, first out.
11 Only now does console.log have its argument. One line of source, eight moves on the stack.
RangeError rather than a wrong answer.Each frame holds that call’s parameters, its local variables, and the position to resume at. That is
what makes recursion work at all — every pending call has its own n.
function fact(n) {
if (n <= 1) return 1;
return n * fact(n - 1); // four frames alive at the deepest point of fact(4)
}
console.log(fact(4)); // 24
Reading a stack trace
The trace is a snapshot of the stack at the moment the error was created. The top line is where it threw; the lines below are its callers, in order.
function parse(input) {
return JSON.parse(input); // throws here
}
function load() {
return parse('{ bad json');
}
try {
load();
} catch (error) {
console.log(error.message);
console.log(error.stack.split('\n').slice(0, 4).join('\n'));
}
// SyntaxError: ...
// at JSON.parse (<anonymous>)
// at parse (file:///app.js:2:15) ← where it threw
// at load (file:///app.js:5:10) ← who called it
Reading from the bottom up tells you the path that got you there; reading from the top down tells you
what broke. Two practical notes: an async boundary cuts the trace, because the caller’s frames are
already gone by the time the continuation runs, and Error.captureStackTrace or a rethrown error
with { cause } is how you preserve context across one.
async function outer() {
try {
await inner();
} catch (error) {
throw new Error('while loading the user', { cause: error }); // keeps the original
}
}
async function inner() {
throw new Error('network down');
}
outer().catch((e) => console.log(e.message, '<-', e.cause.message));
// while loading the user <- network down
Overflow
The stack is a fixed-size region, so there is a maximum number of simultaneous frames — in the region of ten thousand, varying by engine and by how much each frame holds.
function forever(n) {
return forever(n + 1); // nothing ever pops
}
// forever(0); // RangeError: Maximum call stack size exceeded
The error is not about recursion as such. Any sufficiently deep chain does it, including an accidental cycle between two functions:
function a() { return b(); }
function b() { return a(); }
// a(); // RangeError — mutual recursion, no base case
Measuring the limit, which also shows that it is not a fixed language constant:
function depth(n = 0) {
try {
return depth(n + 1);
} catch {
return n;
}
}
console.log(depth() > 5000); // true — the exact number varies per engine and per frame size
Spreading a huge array into a call hits the same wall, because every element becomes an argument in one frame:
const big = Array.from({ length: 200_000 }, (_, i) => i);
// console.log(Math.max(...big)); // RangeError
console.log(big.reduce((max, n) => (n > max ? n : max), -Infinity)); // 199999
The stack and the event loop
Asynchronous callbacks do not sit on the stack while they wait. They are handed to the platform, and the stack empties:
console.log('one');
setTimeout(() => console.log('three'), 0);
console.log('two');
// one / two / three
The timer callback cannot run while console.log('two') is still pending, because the event loop only
looks at the queues once the stack is empty. Which is also why setTimeout(fn, 0) is not “now” —
it is “as soon as the current work finishes”.
The practical consequence is blocking:
function block(ms) {
const end = Date.now() + ms;
while (Date.now() < end) {} // one frame, holding the thread
}
setTimeout(() => console.log('I waited'), 0);
block(500); // nothing else can run for 500ms: no rendering, no clicks, no timers
console.log('done'); // done / I waited
Breaking long work into chunks that each return to the event loop is the standard fix:
async function chunked(items, size = 1000) {
for (let i = 0; i < items.length; i += size) {
items.slice(i, i + size).forEach(() => {});
await new Promise((resolve) => setTimeout(resolve, 0)); // let the stack empty
}
return 'finished without freezing';
}
Frames are not free
Each frame costs memory, which is the real argument for a loop over recursion when the depth scales with the input:
| Loop | Recursion | |
|---|---|---|
| Frames used | one | one per level |
| Memory for depth n | O(1) | O(n) |
| Can overflow | no | yes |
| Suits nested data | awkward | naturally |
// Depth grows with n — a loop:
function sumLoop(n) {
let total = 0;
for (let i = 1; i <= n; i++) total += i;
return total;
}
console.log(sumLoop(1_000_000)); // fine
// Depth bounded by the shape of the data — recursion is right:
const tree = { v: 1, kids: [{ v: 2, kids: [] }] };
const sumTree = (node) => node.v + node.kids.reduce((t, k) => t + sumTree(k), 0);
console.log(sumTree(tree)); // 3
JavaScript specifies tail-call optimisation, which would let a tail-recursive function reuse one frame — but V8 and the other major engines never shipped it, so a tail call costs a frame like any other.
Common mistakes
Reading a stack trace bottom-up for the cause
Mistake. Blaming the function on the last line of the trace.
Why it fails. That is the entry point — usually your own main or a framework’s dispatcher. The
throw happened at the top.
What to do instead. Start at the top for what broke, then read down for how you got there.
Assuming setTimeout(fn, 0) runs immediately
Mistake. Expecting the callback to interleave with the code after it.
Why it fails. The queue is only consulted once the stack is empty, so every synchronous statement
runs first.
What to do instead. Treat setTimeout(fn, 0) as “after the current task”, and keep tasks short.
Fixing an overflow by raising the recursion depth
Mistake. Looking for a flag to make the stack bigger.
Why it fails. --stack-size exists in Node but moves the wall rather than removing it, and
nothing equivalent exists in a browser.
What to do instead. Convert to a loop with an explicit stack, or process in chunks.
Check yourself
2 questions from the bank on what you just read. Answering here does not affect your quiz history.
Every call takes up room somewhere, and that somewhere has a limit.
What happens when this runs?
function loop() {
return loop();
}
loop();What is a stack frame?
Further reading
Everything above is meant to be enough on its own. These are for when you want the full specification of a detail.
Reaching the end of a lecture marks it as read.