The call stack in one screen
The one-page summary of the lesson The call stack. It states the answers, so if you want them to stick, play the lesson first: it makes you predict before it explains.
The points
- Every function call gets a frame on the call stack; the newest is on top.
- A call that calls another is paused until the inner call returns.
- Last in, first out: the deepest call returns first.
- A stack trace is the stack at the moment of the error, newest frame first (Chrome keeps the top 10).
- The stack has a limit: about 5,100 calls of this lesson's code in Chrome, fewer with bigger frames.
- Past it, Chrome throws RangeError: Maximum call stack size exceeded.
- A cycle in data is recursion that never returns: track what you have visited.
What catches people out
- Retrying the same call after a stack overflow repeats the same calls
- A deep but finite tree can overflow too; walk it with a loop and your own stack
The wrong idea, and the right one
Often believed: A function call runs and finishes before the next line, so calls made inside it are separate and only one call is ever open.
What really happens: Each call gets a frame on the call stack and stays there, paused, until every call it made has returned. The last call in is the first out.
Step by step
- Ana's blank page. A crash for one customer's data points at that data meeting the code.
- One frame. Every call gets its own frame on the call stack.
- A call waits. A call that calls another is paused, not finished.
- Three deep. How deep a row is indented is how deep its call is on the stack.
- Read the trace. A stack trace is the call stack at the moment of the error, newest frame first. Chrome keeps the top 10 frames by default.
- Last in, first out. The last call in is the first out.
- The bad record. A cycle in the data is recursion that never returns.
- The retry. Retrying the same call repeats the same calls.
- The fix. Remember what you have drawn: a comment seen once returns at once.
- The rule. A frame stays until every call it made has returned.