Skip to main content

JavaScript Functions

JavaScript Recursion

Written by Published

JavaScript recursion is when a function calls itself to solve a smaller version of the same problem.

Every recursive function needs a stopping point, called the base case.

Without one, the function keeps calling itself until the browser gives up.

Example

Example

javascript

function countdown(n) {
  if (n === 0) {
    return "Done";
  }

  console.log(n);
  return countdown(n - 1);
}

console.log(countdown(3));

Here, the function calls itself with a smaller number each time.

It stops when n reaches 0.

What is Recursion?

Recursion means a function calls itself.

Each call works on a smaller piece of the problem until it reaches a case simple enough to answer directly.

A recursive function always has two parts: the base case that stops it, and the recursive case that shrinks the problem.

Syntax

Syntax

javascript

function name(value) {
  if (baseCase) {
    return result;
  }

  return name(smallerValue);
}

The base case must come first, or the function will never stop.

The Base Case

The base case is the condition that ends the recursion.

Without it you get a "Maximum call stack size exceeded" error.

Example

Example

javascript

function countUp(n, limit) {
  if (n > limit) {
    return "Finished";
  }

  console.log(n);
  return countUp(n + 1, limit);
}

console.log(countUp(1, 3));

Here, the base case stops the function once n passes the limit.

Factorial

Factorial is the classic recursion example, because the definition is recursive.

Example

Example

javascript

function factorial(n) {
  if (n <= 1) {
    return 1;
  }

  return n * factorial(n - 1);
}

console.log(factorial(5));

Here, 5 x 4 x 3 x 2 x 1 gives 120.

Adding Up an Array

Recursion can walk through an array by handling the first item and passing on the rest.

Example

Example

javascript

function sumAll(numbers) {
  if (numbers.length === 0) {
    return 0;
  }

  return numbers[0] + sumAll(numbers.slice(1));
}

console.log(sumAll([1, 2, 3, 4]));

An empty array returns 0, which is the base case.

Nested Data

Recursion is genuinely useful when the data itself is nested to an unknown depth.

A loop cannot easily handle a list that contains other lists.

Example

Example

javascript

function countItems(list) {
  let total = 0;

  for (const item of list) {
    if (Array.isArray(item)) {
      total += countItems(item);
    } else {
      total++;
    }
  }

  return total;
}

console.log(countItems([1, [2, 3], [4, [5, 6]]]));

Here, the function goes as deep as the data does and counts 6 items.

Recursion or a Loop?

A simple countdown is clearer as a loop.

Reach for recursion when the data is nested or the problem is naturally defined in terms of itself.

Example

Example

javascript

function sumLoop(n) {
  let total = 0;

  for (let i = 1; i <= n; i++) {
    total += i;
  }

  return total;
}

console.log(sumLoop(4));

This is the same result as a recursive version, and easier to follow.

Complete Example

Complete Example

html

<!DOCTYPE html>
<html>
<head>
  <title>JavaScript Recursion</title>
</head>
<body>

  <h1>JavaScript Recursion</h1>

  <p id="result"></p>

  <script>
    function factorial(n) {
      if (n <= 1) {
        return 1;
      }

      return n * factorial(n - 1);
    }

    document.getElementById("result").innerHTML =
      "Factorial of 6 is " + factorial(6);
  </script>

</body>
</html>

Try It Yourself

Run the above example in the Try It Editor.

Try a different number:

Change 6 to 8 and see how quickly the answer grows.

Important Points

  • Recursion is a function that calls itself.
  • Every recursive function needs a base case to stop it.
  • Each call must work on a smaller version of the problem.
  • Missing the base case gives a "Maximum call stack size exceeded" error.
  • Use recursion for nested data; use a loop for simple counting.

Conclusion

JavaScript recursion solves a problem by breaking it into smaller copies of itself.

The base case is what keeps it from running forever.

Understanding recursion helps you work with nested data such as trees and folders.