Glossary / Call stack

Call stack

The call stack tracks currently executing JavaScript function calls. Each call creates an execution context (parameters, local bindings, and control state) and pushes it onto the stack; returning or throwing removes that frame and resumes its caller. In a typical JavaScript agent, one stack executes JavaScript at a time, so a long-running synchronous function delays other work on that agent, including input handling and rendering on the browser main thread.

Stack behavior and async boundaries

function first() { second(); }
function second() { throw new Error("failure"); }
first(); // stack: first -> second; the exception unwinds both frames

A stack trace shows a snapshot of call relationships at failure time. Promise, timer, and event callbacks usually execute later on a fresh stack after their scheduling call has returned. Browsers and runtimes may provide async stack traces that connect these jobs for debugging, but the async continuation is not literally kept on the original synchronous call stack.

Deep recursion can exceed the engine’s stack limit and produce RangeError; JavaScript does not provide broadly relied-upon proper tail-call optimization. Recursive code should be bounded or rewritten iteratively when input depth may be large. Never block the stack with synchronous waits or long CPU loops in latency-sensitive code.

Debugging use

Use breakpoints, stack traces, and performance profiles to identify the current call path and expensive frames. An async stack trace is useful context but may be incomplete or optimized. When diagnosing reentrancy, remember that synchronous callbacks can call back into code before the original stack unwinds.

Interview questions

  1. What does the call stack contain? Active execution contexts for current synchronous calls.
  2. Does a Promise continuation stay on the original stack? No; it runs later as a queued job, typically with a fresh stack.
  3. What causes stack overflow? Excessive nested calls/recursion beyond engine limits.
  4. Why does a long callback hurt UI responsiveness? The main thread cannot process other queued work until it returns.

References