Recursion in Javascript

Rumman Ansari   Software Engineer   2023-03-26   5883 Share
☰ Table of Contents

Table of Content:


Introduction to the JavaScript recursive function

A recursive function is a function that calls itself. We will take the classic factorial function for the demonstration.

in Mathematics, the factorial of a non-negative integer is the product of all positive integer less than or equal to it. The factorial of the integer n is denoted by n!

For example, the factorial of 5 is calculated as follows:

 5! = 5 x 4 x 3 x 2 x 1 = 120 

To develop a factorial function in JavaScript, you simply use a for loop as follows:

function factorial(n) {
    var result = 1;
    for (let i = n; i > 1; i--) {
        result *= i;
    }
    return result;
}

This function is clean and straightforward.

However, it is more readable if you develop the factorial function using the recursion technique. See the following recursive factorial function:

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


This is how it works. If n is equal to one or zero, the factorial of n is 1; otherwise, the factorial of n is the product of n and factorial of n - 1.

The function seems to work fine initially. However, as mentioned in the Function type tutorial, the name of a function is a pointer pointing to the function object.

The following code causes an error.

 
var fac = factorial;
factorial = null;
console.log(fac(5)); // TypeError: factorial is not a function

How the script works.

  • First, assign the variable named  fac to the factorial function name.
  • Second, set the factorial pointer to null.
  • Third, call the  fac function.

Because inside the function, we referenced to the factorial name which was set to null at the time of calling the function, therefore we got a TypeError error.

To resolve it, you can use a named function expression as follows:

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

In this case, the  pf function name is visible inside the function itself and it remains the same even if you assign the function to another variable. As a result, the recursive call will work correctly.

Here is the test of the factorial function:

var fac = factorial;
factorial = null;
console.log(fac(5)); // 120

In this tutorial, we have shown you how to develop JavaScript recursive functions by implementing the factorial calculation function.