Trusted answers to developer questions

How to find the factorial of a number in JavaScript

Get Started With Data Science

Learn the fundamentals of Data Science with this free course. Future-proof your career by adding Data Science skills to your toolkit — or prepare to land a job in AI, Machine Learning, or Data Analysis.

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(n1)...1factorial(n)=n * (n-1) * ... * 1

It can also be thought of as:

factorial(n)=nfactorial(n1)factorial(n)=n * factorial(n-1)

Note: The factorial of 0 is 1.


Example

svg viewer

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){
let answer = 1;
if (n == 0 || n == 1){
return answer;
}
else if(n > 1){
for(var i = n; i >= 1; i--){
answer = answer * i;
}
return answer;
}
else{
return "number has to be positive."
}
}
let n = 4;
answer = factorial(n)
console.log("Factorial of " + n + " : " + 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){
if(n < 0){
return "number has to be positive."
}
//base case
if(n == 0 || n == 1){
return 1;
//recursive case
}else{
return n * factorial(n-1);
}
}
let n = 4;
answer = factorial(n)
console.log("Factorial of " + n + " : " + answer);

RELATED TAGS

javascript
recursion
iteration
Copyright ©2024 Educative, Inc. All rights reserved
Did you find this helpful?