🟒 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