Skip to content
dreamcode
dreamcode
Map
Recursion
Lesson 38 of 48
+15 XP on finish
JS ALGORITHMSChapter 8 · JS Algorithms

Recursion

A recursive function calls itself on a smaller piece of the problem. It needs a base case that stops the calls and a recursive case that moves toward it. Recursion fits problems that are nested by nature, such as arrays inside arrays or folders inside folders.

Worked example

How it reads

  • Base case: n <= 1 answers without another call
  • flatten recurses only into items that are arrays
  • Each call waits for the smaller call, then builds its own answer
Common mistakes
  • No base case, or a call that does not shrink the problem, ends in RangeError: Maximum call stack size exceeded.
Cloud tip: Assume the smaller call already works, and only decide how to use its answer.
index.js
JAVASCRIPT
real JavaScript, runs in your browser
Console
Run your code to see its output here.
YOUR TURN

Make sumTo(n) recursive so it adds every number from n down to 1. sumTo(4) should print 10.

Press Run to check your work.