Sikau

Advanced JavaScript · Day 2 · about 25 min

Recursion

Functions that call themselves.

A problem inside a problem

Opening a set of nesting dolls: open one, and inside is a smaller one — repeat until you reach the tiniest. Some problems are naturally like this. A function that solves a smaller version of itself is recursive.

Base case and recursive case

function countdown(n) {
  if (n === 0) {
    console.log("Liftoff!");
    return;
  }
  console.log(n);
  countdown(n - 1);
}
countdown(3);
function factorial(n) {
  if (n <= 1) return 1;
  return n * factorial(n - 1);
}
console.log(factorial(5));

The rest of this lesson

  • Where recursion shines: nested dataexplain
  • Thinking recursivelyexplain
  • Predict the outputpredict
  • Trace itpredict
  • Your turnwrite code
  • Challengechallenge
  • Badge quizquiz
  • What you learnedrecap

Continue this lesson free — run real code in your browser

Continue with Google

See all 27 lessons of Advanced JavaScript