Walking a tree: a nested menu
No loop could easily follow branches of unknown depth; recursion handles any depth with the same few lines.
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.
Write power(base, exp) recursively for whole-number exp >= 0 (base case: exp === 0 returns 1).
Write reverse(text) recursively, so reverse("abc") returns "cba".
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
What two parts does every recursive function need, and why?
What is the call stack, and what happens on it during factorial(3)?
What causes RangeError: Maximum call stack size exceeded, and how do you prevent it?
When would you choose recursion over a loop, and vice versa?
Preview
Console
Nothing logged yet.Expected console output
items: 6
levels: 4