Skip to the workspace
Pebellslearn by building
Functions  ›  Lesson

Recursion

Recursion 12 min

javascript / Recursion

Explore each scene at your own pace.

01 · Recursion

Recursion

Recursion

Recursion solves a problem by calling the same function on a smaller subproblem. A base case stops further calls.

Show both why another call is needed and how each call gets closer to stopping.

See the mechanism

Walk through the modelRecursionAuthored snapshots of the example; use Run below to test the code.
sumTo(3)sumTo(2) → sumTo(1) → sumTo(0)
Each call reduces the input by one.
1 of 3

Follow one example

javascript

sumTo(3) waits for sumTo(2), which waits for sumTo(1), which reaches sumTo(0). The base case returns 0; the waiting additions then return 1, 3 and 6. This version assumes a small nonnegative integer. Negative input does not approach the base case, and deep recursion can overflow the call stack.

Predict, change and check

Predict: What happens if n - 1 is replaced by n in the recursive call?

Test your explanation: Do not run that unbounded version in a page. Instead explain the unchanged argument, then test the safe base cases 0 and 1 and compare with a loop.

The tasks below ask you to explain that result and apply the idea to different inputs.

Apply and distinguish

Prove the work becomes smaller

A recursive function needs a base case and a path that moves toward it. An unchanged recursive argument can overflow the stack instead of finishing. Trace a tiny input and include the base-case return, because that value travels back through waiting callers.

A recursive implementation is not automatically asynchronous or more efficient than a loop. For unbounded input depth, an explicit stack or iterative strategy can avoid call-stack limits. Scope and closures explain retained bindings; recursion explains repeated calls. Do not combine these distinct ideas under a single 'async' explanation merely because their files share a folder.

Check your understanding: State the input contract, identify the operation that changes the result, and give one boundary input that would distinguish the correct rule from the mistake described above.

Scene 1 of 2
Project context and further resources
Additional resources
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.