Pebellslearn by building
0%
RoadmapsMatrixCoursesSandboxSign in
Functions  ›  Lesson

Scope and the Function (Call) Stack

Scope & Function Stack 10 minEvery function call pushes a frame onto the call stack; the frame is popped only when that call finishes, so calls nest like a stack of plates, and a function that calls itself without ever stopping overflows the stack with a RangeError.

Scope and the Function (Call) Stack

In short: every function call pushes a frame onto the call stack — a record of where to resume once that call finishes. Frames stack like plates: the newest call sits on top, and it must finish (be popped) before the call underneath it can continue. A function's own variables live only in its own frame — that's scope — and a function that calls itself without ever stopping just keeps pushing frames until the stack overflows.

The call stack drawn as a stack of plates: main() at the bottom (first call), total(cart) above it, gstRate(900) on top — newest call at the top, first call at the bottom, each finishing and popping before the one under it can continue

Watching the stack build up

Every nested call adds a plate; every return removes one:

javascript

main() is pushed first. It calls total(cart), pushed on top. total calls gstRate once per item, each pushed and popped in turn before total can finish its reduce and return its own value to main. At no point does a lower frame continue before the one above it is done.

Recursion: a function calling itself, on purpose

A function calling itself is normal — as long as it has a way to stop:

javascript

Each call to countdown pushes a new frame with its own n. n <= 0 is the base case — the condition that stops the recursion and lets every pushed frame finally pop, one by one, back down to the original call.

Recursion with no base case overflows the stack

Remove the stopping condition, and the stack has nowhere to stop growing:

javascript

Every call immediately calls another before it can return, so no frame ever pops. The stack grows until it hits the engine's fixed size limit, and JavaScript throws RangeError: Maximum call stack size exceeded — the practical proof that the call stack is a real, limited structure, not an infinite list.

Quick practice

quick drill

When function A calls function B, which frame is on top of the call stack while B is running?

quick drill

What must a recursive function have to avoid a stack overflow?

quick drill

What error does JavaScript throw when the call stack grows too large?

Practice — level up

0/1 solved

Write your answer, then compare it with a rubric and a model answer.

ExplainWhy infinite recursion crashes

function recurseForever(n) { return recurseForever(n + 1); } eventually throws RangeError: Maximum call stack size exceeded. Explain why, in terms of the call stack, and what recursive functions normally have that this one is missing.