AI Hints
Home›JavaScript Tutorial›Callbacks and Recursion
JavaScript · Lesson 39 of 138

Recursion

Functions calling themselves.

⏱ 2 min read▶ Video at 46:43🎓 Free
Watch this lesson in the JavaScript courseWatch on YouTube ↗Full JavaScript course

A function can call itself. That's called recursion. It's a neat way to solve problems that contain smaller copies of themselves, like counting down, or exploring folders inside folders.

Recursion
From the video: Recursion
  • A function calls itself
  • Recursion
  • Problems inside problems

Countdown and factorial

Countdown prints N, then calls itself with N minus one. The base case, N equals zero, stops it. Factorial multiplies N by the factorial of N minus one, until N reaches one. Run it.

app.jsjavascript
function countdown(n) {
  if (n === 0) {
    console.log("Lift off!");
    return;
  }
  console.log(n);
  countdown(n - 1);
}
countdown(3);

const factorial = n => (n <= 1 ? 1 : n * factorial(n - 1));
console.log("5! =", factorial(5));
Output
3
2
1
Lift off!
5! = 120

Always have a base case

Every recursive function needs a base case, a condition where it stops calling itself. Without one, it calls itself forever, until JavaScript runs out of room and throws a range error, maximum call stack size exceeded. Each call should move closer to the base case.

keyvalue
Recursive casecalls itself, smaller
Base casestops
No base casestack overflow
Good fornested data

Summing nested lists

Recursion shines with data that's nested inside itself. Here, a list can contain numbers, or more lists. Sum all adds up the numbers. When it finds a list, it calls itself on that list. However deep the nesting goes, the same few lines handle it. Run it.

app.jsjavascript
function sumAll(items) {
  let total = 0;
  for (const item of items) {
    if (Array.isArray(item)) total += sumAll(item);
    else total += item;
  }
  return total;
}

console.log(sumAll([1, [2, 3], [4, [5, [6]]]]));
Output
21

Summary

Recursion is a function calling itself, with a base case to stop. Next, pure functions.

Key takeaways
  • Call yourself
  • Base case stops it
  • Move towards it
Next up: Pure Functions — no side effects