Course progress0%
Course content

Module 1

Module 2

Module 3

Module 4

Module 5

Module 6

Module 7

Module 8

Module 9

Module 10

Module 11

Module 12

Module 13

Module 14

Module 15

Module 16

Module 17

Module 18

25 min

The Call Stack

Trace nested function calls and returns

By the end of this lesson

  • Trace nested function calls and returns
  • Read a stack as pending work

Follow one request through functions

A quote calls a subtotal function, which returns a value used by the quote. Which function is paused while the subtotal is being calculated?

function calculateSubtotal(price, quantity) {
  return price * quantity;
}
function calculateQuote(price, quantity) {
  const subtotal = calculateSubtotal(price, quantity);
  return subtotal + 5;
}
console.assert(calculateQuote(20, 2) === 45);

The call stack tracks active function calls. Calling calculateQuote adds a frame. Calling calculateSubtotal adds another above it. Returning 40 removes the inner frame and resumes the quote, which returns 45. The most recently entered unfinished call returns first.

Enter calculateQuote
  Enter calculateSubtotal
  Return 40 to calculateQuote
Return 45 to the caller

Each call has its own parameters and local variables. The stack is a model of pending work, not a history of every call that has ever happened.

Guided observation

Pause inside calculateSubtotal with the debugger from the previous module. Inspect the call stack: the caller is waiting for its result. A stack trace in an error tells you a similar story about the calls active when the failure occurred.

Independent exercise

Add a formatQuote function that calls calculateQuote and returns a text label. List the order in which the three functions enter and return. Then explain what happens if the deepest call throws instead of returning.

Correction

Enter formatQuote, calculateQuote, calculateSubtotal; return in reverse order. If the deepest call throws, the normal additions and formatting do not continue along that path. Control searches outward for a matching catch.

Review

A function that repeatedly calls itself without a stopping rule can exhaust the stack. We do not need recursion for these exercises. Prefer a clear loop until recursive decomposition solves a problem you can explain.

Lesson complete?

Your progress is saved on this device.