JavaScript Fundamentals / Functions

Recursive Function

🔄 Recursion in Action

A recursive function is a function that calls itself repeatedly to solve a problem by breaking it into smaller parts. This process, known as recursion, continues until a specific stopping condition (called the base case) is met, which prevents the function from running forever.


🧠 Why Use Recursion?

Recursive functions are useful for:

  • Breaking down complex problems into simpler subproblems.

  • Solving problems involving:

    • Mathematical calculations (factorials, sum, Fibonacci).

    • Data structures like trees, graphs.

    • Algorithms such as quicksort, binary search, backtracking.

Example :

Suppose that you have a function called recurse(). The recurse() is a recursive function if it calls itself inside its body, like this:

function recurse() {
    // ...
    recurse();
    // ...
}

A recursive function always has a condition to stop calling itself. Otherwise, it will call itself indefinitely. So a recursive function typically looks like the following:

function recurse() {
    if (condition) {
        // Base case: stop here
    } else {
      recurse(); // Recursive call
    }
}
  • Base Case: The condition that stops the recursion.

  • Recursive Case: The function calls itself to solve a smaller problem.

Without a base case, the function calls itself forever, causing a RangeError.


✅ Example 1: Count Down Using Recursion

Without Base Case

Here ,

To count down from the number 3 to 1, you can:

  1. show the number 3.

  2. and call the countDown(2) that shows the number 2.

  3. and call the countDown(1) that shows the number 1.

function countDown(fromNumber) {
     console.log(fromNumber);
     countDown(fromNumber - 1); // No base case!
}

countDown(3);

This countDown(3) will run until the call stack size is exceeded, like this and give output :

This goes into infinite recursion because there’s no condition to stop it.

3
2
1
0
-1
-2
...
Uncaught RangeError: Maximum call stack size exceeded

The countdown will stop when the next number is zero.

With Base Case

So, we need to add Condition as follows:

function countDown(fromNumber) {
    console.log(fromNumber);
    
    let nextNumber = fromNumber - 1;

    if (nextNumber > 0) {
        countDown(nextNumber);
    }
}
countDown(3);
3
2
1

Explanation:

  • countDown(3) → prints 3, calls countDown(2)

  • countDown(2) → prints 2, calls countDown(1)

  • countDown(1) → prints 1, doesn't call again (nextNumber is 0)

  • Recursion stops!


✅ Example 2: Sum of First n Natural Numbers Using Recursion

Calculate the sum of numbers from 1 to n.

Formula (Recursive)

sum(n) = n + sum(n - 1)