JavaScript – Recursive function example

What is a recursive function

A recursive function is a function that calls itself. It keeps doing so until it reaches a specific stopping condition (known as the base case).

This approach makes it possible to solve problems that involve repeating the same operation on smaller pieces of data, such as summing elements in a nested array (where arrays contain other arrays), traversing a tree structure (for example, categories, menus, or a file system), or navigating through nested JSON objects.

Key principles

  • The function calls itself with new (smaller) input data.
  • A base case stops further calls to prevent an infinite loop.

Example of a recursive function that sums all elements in an array:

function sumArray(array) {
    let sum = 0;

    for (const element of array) {
        if (Array.isArray(element)) {
          // If the element is an array, call the function again (recursion)
          sum += sumArray(element);
        } else {
          // If it's a number, add it to the total sum
          sum += element;
        }
    }

    return sum;
}

// Example usage:
const data = [1, [2, [3, 4], 5], 6];
console.log(sumArray(data)); // Output: 21

The sumArray function goes through all elements of the array. If an element is another array, the function calls itself (recursion). If the element is a number, it adds it to the total. This process repeats until all deeply nested numbers are reached. The code works regardless of how deeply the arrays are nested – there’s no need to write multiple loops.

Infinite recursion

When using recursive functions, it’s important to watch out for the risk of infinite recursion. This can happen when a proper stopping condition is missing or when the condition is never met. If a function keeps calling itself without ever reaching the point where it should stop, it will run indefinitely until the browser or interpreter (such as PHP) terminates execution with a stack overflow error.