Command Palette

Search for a command to run...

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

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.

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?

Walking a tree: a nested menu

Preview

Press Run to see the page.

Console

Nothing logged yet.

Expected console output

items: 6
levels: 4