**Summary**: this tutorial shows you how to use recursion technique to develop a JavaScript recursive function, which is a function that calls itself.

## 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 Math, a 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!`

The following formula shows how to calculate the factorial of a non-negative integer `n`

:

For example, the factorial of `5`

is calculated as follows:

1 | 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:

1 2 3 4 5 6 7 | function factorial(n) { var result = 1; for (let i = n; i > 1; i--) { result *= i; } return result; } |

This function is clean and readable enough.

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

1 2 3 4 5 6 7 | 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.

1 2 3 | 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:

1 2 3 4 5 6 7 | 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 if you assign the function to another variable. As the result, the recursive call will work correctly.

1 2 3 | 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.