What is the Call Stack?
The call stack is the structure the JavaScript engine uses to track which function is running: each call pushes a frame on top, each return pops it off, and because there is only one stack, only one piece of JavaScript runs at a time.
How it works
- The script starts and the global context sits at the bottom.
- Calling
a()pushesa. Ifacallsb(),bis pushed on top. - When
breturns, it is popped andacontinues from where it left off. - When the stack is empty, the event loop can run the next queued task.
What you see in practice
- Stack traces in errors are a snapshot of the call stack at the moment of the throw, top frame first.
- Stack overflow: unbounded recursion keeps pushing frames until the engine throws
RangeError: Maximum call stack size exceeded. - Blocking: a long synchronous loop keeps its frame on the stack, so clicks, timers and rendering wait until it finishes.
Relationship with async code
setTimeout, fetch and promises do not put their callbacks on the stack directly. They queue them, and the event loop pushes each callback onto the stack only when the stack is empty. That is why setTimeout(fn, 0) still runs after the current synchronous code.
Debugging
Browser DevTools show the call stack when paused at a breakpoint; async stack traces even connect a callback to the code that scheduled it.
Code example
1function third() {2 console.log(new Error("where am I?").stack.split("\n").slice(1, 4).map((l) => l.trim().split(" (")[0]));3 // [ "at third", "at second", "at first" ] - top of the stack first4}5function second() {6 third();7}8function first() {9 second();10}11first();1213// Stack overflow from unbounded recursion14function countDown(n) {15 return countDown(n + 1); // no base case16}17try {18 countDown(0);19} catch (e) {20 console.log(e.name, "-", e.message); // RangeError - Maximum call stack size exceeded21}2223// Async callbacks wait for an empty stack24setTimeout(() => console.log("3. timer: runs after the stack is empty"), 0);25console.log("1. synchronous");26for (let i = 0; i < 1e6; i++); // busy work keeps the stack occupied27console.log("2. still synchronous");
Practice this question
Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the JavaScript set.