Recursive Function

suggest change

A recursive function is simply a function, that would call itself.

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

The above function shows a basic example of how to perform a recursive function to return a factorial. The base case treats every n <= 1 as 1, including negative numbers, so it is only a factorial for non-negative integers.

Another example, would be to retrieve the sum of even numbers in an array.

function countEvenNumbers (arr) {
    // Sentinel value.  Recursion stops on empty array.
    if (arr.length < 1) {
        return 0;
    }
    // shift() removes the first element and returns it.
    // The caller's array is emptied as the recursion continues.
    const value = arr.shift();

    // `value % 2 === 0` tests if the number is even or odd
    // If it's even we add one to the result of counting the remainder of 
    // the array.  If it's odd, we add zero to it.
    return ((value % 2 === 0) ? 1 : 0) + countEvenNumbers(arr);
}

It is important that such functions make some sort of sentinel value check to avoid infinite loops. In the first example above, when n is less than or equal to 1, the recursion stops, allowing the result of each call to be returned back up the call stack.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents