EasyFunctions📖 Theory Question

What is recursion and what causes a stack overflow?

💡

Hint

Function calling itself — needs a base case; too many calls = call stack exhausted

Full Answer

Recursion is when a function calls itself. Every recursive function needs:

  1. A base case — a stopping condition
  2. A recursive case — that moves toward the base case
// Factorial
function factorial(n) {
  if (n <= 1) return 1;         // base case
  return n * factorial(n - 1); // recursive case
}
factorial(5); // 120

// Flatten nested array
function flatten(arr) {
  return arr.reduce((acc, item) =>
    Array.isArray(item)
      ? acc.concat(flatten(item)) // recurse
      : acc.concat(item),
  []);
}
flatten([1, [2, [3]]]); // [1, 2, 3]

Stack overflow: Each recursive call adds a stack frame. Without a base case (or with very deep recursion), the call stack fills up:

function infinite(n) {
  return infinite(n + 1); // no base case!
}
infinite(1); // RangeError: Maximum call stack size exceeded
💡 Tail Call Optimization (TCO) can theoretically prevent stack overflow for tail-recursive calls, but TCO is only reliably supported in Safari. For deep recursion, use iteration or trampolining.

More Functions Questions

EasyWhat is the difference between call, apply, and bind?EasyHow do arrow functions differ from regular functions?EasyWhat is a pure function and why does it matter?EasyWhat are Higher-Order Functions (HOF)?

Practice this in a timed sprint →

5 free questions, no signup required

⚡ Start Sprint