Related Tags

javascript
recursion
iteration

# How to find the factorial of a number in JavaScript

The factorial of a non-negative​ number,n, is computed as the product of all integers between 1 and n (both inclusive).

$factorial(n)=n * (n-1) * ... * 1$

It can also be thought of as:

$factorial(n)=n * factorial(n-1)$

Note: The factorial of 0 is 1.

## Approaches

There are two ways to compute the factorial of a number in JavaScript.

1. Iterative
2. Recursive

Both of these approaches will be explored below.

### 1. The iterative approach

Keeping in mind the first definition of a ​factorial, the variable i is initially set equal to n and is gradually decremented to 1. In each step, the result of the multiplication is stored in the variable answer.

The table below shows how the values of i and answer vary with each iteration.

i answer
4 4
3 4 * 3 = 12
2 12 * 2 = 24
1 24 * 2 = 1

Pro: Takes less memory than the recursive implementation.

Con: The code is lengthier than that of the recursive implementation.

function factorial(n){
if (n == 0 || n == 1){
}else{
for(var i = n; i >= 1; i--){
}
}
}
let n = 4;
console.log("The factorial of " + n + " is " + answer);

### 2. The recursive approach

As stated above, the factorial of n can be found by finding the factorial of a number one less than n, and then multiplying this answer with n. So the factorial of n-1 can be thought of as a subproblem that needs to be computed first.

The table below shows the value returned by each function call.

function call return value
factorial(1) 1 (base case)
factorial(2) 2 * 1 = 2
factorial(3) 3 * 2 = 6
factorial(4) 4 * 6 = 24

Pro: Shorter and cleaner code.

Con: Greater memory requirements as all the function calls remain on the stack until the base case is reached.

function factorial(n){
//base case
if(n == 0 || n == 1){
return 1;
//recursive case
}else{
return n * factorial(n-1);
}
}
let n = 4;
console.log("The factorial of " + n + " is " + answer);

RELATED TAGS

javascript
recursion
iteration