Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 3.8 — Recursion
JavaScript · Example 3 of 3

Stack overflow and repeated work

The exact overflow depth differs between browsers, so the example only checks it's large. Memoisation cuts 21,891 calls to 39.

A recursive function solves a problem by calling itself on a smaller piece of it, until it reaches a base case simple enough to answer directly; every pending call waits on the call stack, and without a base case the stack overflows.

Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.

Ready for more? This phase has 6 hands-on exercises with automatic checks.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Write power(base, exp) recursively for whole-number exp >= 0 (base case: exp === 0 returns 1).

02

Write reverse(text) recursively, so reverse("abc") returns "cba".

03

Write sumNested(list) that adds all numbers in an array that may contain arrays at any depth, like [1, [2, [3, 4]], 5].

Explain it without notes

01

What two parts does every recursive function need, and why?

02

What is the call stack, and what happens on it during factorial(3)?

03

What causes RangeError: Maximum call stack size exceeded, and how do you prevent it?

04

When would you choose recursion over a loop, and vice versa?

Stack overflow and repeated work

Console

(nothing was printed)

Expected console output

RangeError: Maximum call stack size exceeded
more than 1000 frames? true
fib(20) = 6765 using 21891 calls
fastFib(20) = 6765 using 39 calls