awesome-everything RU
↑ Back to the climb

Base CS from zero

Functions and the call stack: code and trace reading

Crux Read four small TypeScript snippets, trace the stack frame-by-frame, count recursion depth, and predict what parameter passing and return actually do.
Your altitude — climbing toward senior
ZeroJuniorMiddleSenior
You are at middle altitude — in the sky
◷ 14 min

Reading the call stack from the code is the skill the whole unit builds toward. For each snippet, run it in your head: push a frame on every call, pop one on every return, and watch where the values flow.

Goal

Practise tracing real code the way the machine runs it — counting live frames, predicting recursion depth, and reasoning about what crosses the frame boundary when arguments go in and a value comes back.

Snippet 1 — nested calls and stack depth

function inner(): void {
  let c = 3;          // inner's only local
}

function outer(): void {
  let b = 2;          // outer's only local
  inner();            // pushes inner's frame
}

function main(): void {
  let a = 1;          // main's only local
  outer();            // pushes outer's frame
}

main();
Quiz

At the instant inner is executing let c = 3, how many frames are on the stack and which holds a = 1?

Snippet 2 — parameter passing (pass-by-value)

function bump(x: number): void {
  x = x + 100;        // reassigns bump's own copy of x
}

function main(): void {
  let v = 1;
  bump(v);            // argument 1 copied into bump's x
  // what is v here?
}
Quiz

After bump(v) returns, what is the value of v in main, and why?

Snippet 3 — recursion depth

function sumTo(n: number): number {
  if (n === 0) return 0;        // base case
  return n + sumTo(n - 1);      // recursive case
}

sumTo(4);
Quiz

For sumTo(4), what is the maximum number of frames live at once, and what value is returned?

Snippet 4 — missing base case

function blow(n: number): number {
  return n + blow(n + 1);   // no base case: n only grows
}

blow(0);
Quiz

What happens when blow(0) runs, and what is the underlying cause?

Recap

Every snippet is read by running the stack in your head: nested calls keep all callers’ frames live below the active one; a copied argument means reassigning a parameter never touches the caller’s variable; a recursive call pushes a new frame per level so peak depth is the number of nested live calls (including the base case); and a recursion with no reachable base case grows the stack without bound until it overflows. Trace push-on-call, pop-on-return, and the answers fall out.

Continue the climb ↑Functions and the call stack: build a stack tracer
shortcuts expand
search
K
prev piece
k
next piece
j
cycle tier
t
this menu
?
sources3
expand
  1. 01
  2. 02
  3. 03

Trademarks belong to their respective owners. Editorial reference only.