Recursive Functions in JavaScript

📌 What is Recursion?

A recursive function is a function that calls itself in order to solve a problem. Each recursive call breaks the problem down into smaller chunks — until it reaches a base case that stops the recursion. 🧠

>>“To understand recursion, you must first understand recursion.” — Anonymous

🔍 Why Use Recursion?

Recursion is especially useful for problems that can be divided into similar subproblems, such as:

  • Traversing a tree structure 🌳
  • Calculating factorials 📐
  • Generating Fibonacci sequences 📊
  • Solving puzzles (e.g., Tower of Hanoi) 🧩

🧪 Example: Factorial Function

Recursive Factorial

function factorial(n) {
  if (n === 0) {
    return 1; // base case
  }
  return n * factorial(n - 1); // recursive call
}

console.log(factorial(5)); // 120

In the example above, the function keeps calling itself with n - 1 until n === 0, which is the base case.

⚠️ Important Concepts

  • Base case: The condition under which recursion ends.
  • Recursive case: The part where the function calls itself.
  • A missing base case causes Maximum call stack size exceeded errors.

Note

⚠️ Always ensure your recursive function has a clear base case to avoid infinite recursion!

🔥 Example: Fibonacci Sequence

Recursive Fibonacci

function fibonacci(n) {
  if (n <= 1) return n;
  return fibonacci(n - 1) + fibonacci(n - 2);
}

console.log(fibonacci(6)); // 8

This function calculates the nth number in the Fibonacci sequence by recursively summing the two previous values.

⚡ Tail Recursion (Advanced)

Some JavaScript engines optimize tail-recursive functions (where the recursive call is the last thing executed). This can help avoid stack overflows.

Tail Recursive Example

function factorial(n, acc = 1) {
  if (n === 0) return acc;
  return factorial(n - 1, acc * n);
}

Note

🧪 Tail call optimization is not guaranteed in all JavaScript environments.

✅ Summary

  • Recursive functions call themselves 🌀
  • Always define a base case to avoid infinite loops
  • Great for solving divide-and-conquer problems
  • Be mindful of performance and stack size 🧱

📚 References

>>“Recursion unlocks elegant solutions to complex problems — one step at a time.” 🧗