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.

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;
    }
    // The shift() method removes the first element from an array 
    // and returns that element. This method changes the length of the array.
    var 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) + countEvens(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:


Functions:
* Syntax
* Recursive Function

Table Of Contents
11 Arrays
12 Objects
14 Classes
16 Map
17 Set
24 Loops
25 Functions
27 Date
29 Scope
30 AJAX
35 Cookies
41 JSON
44 Fetch
45 Modules
46 Screen
64 Console
68 Symbols
73 Modals
76 Events
86 Proxy
89 WeakMap
90 WeakSet
102 Tilde