Frontend engineer path · The language · Topic 1 of 17

The call stack

Not started

Your code runs on a single thread, one function at a time. Calling a function puts a frame holding its arguments and local variables on top of the stack; returning takes it off. Recurse too deeply and the engine gives up with a RangeError ("Maximum call stack size exceeded").

Why it matters: It is how you read a stack trace, and why a long-running loop freezes the whole page.

1

How it works

The explanation, with examples you can run.

Reading a stack trace

When an error is created it records the frames that are on the stack at that moment, newest first. The top line is where it happened; every line under it is the caller of the line above. Run this and read the output from the top down: c, called by b, called by a, called by the script itself.

⌘/Ctrl + Enter
OutputNot run yet

Press Run to see what your code prints, in order.

Runs in this browser, in an isolated frame with no access to this page. console.log, info, warn and error are shown; code runs as a classic script, so use an async function for await.

Run to completion

While a function is on the stack, nothing else runs: not a click handler, not a timer that is already due. A loop that keeps the thread busy for half a second delays everything else by half a second, which is why one slow function makes a page feel frozen.

⌘/Ctrl + Enter
OutputNot run yet

Press Run to see what your code prints, in order.

Runs in this browser, in an isolated frame with no access to this page. console.log, info, warn and error are shown; code runs as a classic script, so use an async function for await.

Too deep

The stack has a fixed size. A function that calls itself without a way to stop fills it up, and the engine throws instead of crashing.

⌘/Ctrl + Enter
OutputNot run yet

Press Run to see what your code prints, in order.

Runs in this browser, in an isolated frame with no access to this page. console.log, info, warn and error are shown; code runs as a classic script, so use an async function for await.

If you need to process something very deep (a long linked list, a huge tree), use a loop with your own array as the stack instead of recursion.

2

Check yourself

3 questions. Get them all right to finish this topic.

  1. 1.Infinite recursion in V8 (Chrome, Node) ends with which error?
  2. 2.In a stack trace, which line is the place where the error was created?
  3. 3.A timer is due while a loop is still running. When does its callback run?

0 of 3 right so far. Get all three to finish this topic.