# Factorial of a number using JavaScript

In this article, we shall look at the different methods of finding factorial of a number using JavaScript. Before we do that, let us first understand what factorial of a number is.

## Table of Contents

- What's a Factorial?
- Using simple iteration
- Using recursive function

## What's a Factorial?

In this article, we shall look at the different methods of finding factorial of a number using JavaScript. Before we do that, let us first understand what factorial of a number is.

The factorial of a positive integer n is the product of all positive integers less than or equal to n.

The factorial of a positive number n is given by n!(read as n factorial) where,

```
(n!) = 1 * 2 * 3 * 4.....n
```

For example,

The factorial of 4 is equal to 1 * 2 * 3 * 4 = 24

Also, factorials do not exist for negative numbers and the factorial of 0 is 1.

Now that we know what a factorial is, let us understand different methods of finding the factorial of a number using JavaScript.

## Using simple Iteration

In this method, we just use a for loop and iterate n times and multiply all the numbers from 1 to n. Where n is the number we want to find the factorial for.

```
var number = 2
if (number < 0) {
console.log('Error');
}
// if number is 0
else if (number === 0) {
console.log(`The factorial of ${number} is 1.`);
}
// if number is positive
else {
let fact = 1;
for (i = 1; i <= number; i++) {
fact *= i;
}
console.log(fact);
}
//When number = 2; Output: 2
//When number = 3; Output: 6
//When number = 0; Output: 1
//When number = -1; Output: Error
```

In the above program, an error message is shown when the user enters a negative number. When the user enters 0, the factorial is 1 and for a positive integer, a for loop is used to iterate from 1 to the number entered and all the numbers are multiplied to find the factorial with the product being stored in the fact variable after each iteration.

## Using a recursive function

In this method, we use the concept of the recursive function. Where a recursive function is a function that calls itself during its execution. These functions usually solve the same problem using fewer lines of code.

In the below example, we make use of the following formula where,

n! = n*(n-1)!

If you look at it closely and expand the (n-1)! it is the same as what we have discussed at the beginning of this article.

```
function factorial(n) {
//base case for 0!
if (n == 0 || n == 1) {
return 1;
//recursion case
} else {
return n * factorial(n - 1);
}
}
let n = 5;
answer = factorial(n)
console.log(answer);
//Output: 120
```