Blog for web developers

Get factorial with JavaScript

In this article we will get the factor with JavaScript. I am going to show you a quick and different way to get factorial with JavaScript.

Factorial with loop

Lets learn first what is the factorial in Mathematics. Factorial is simply the multiplication of series of number till the given number starting from 1. Let us suppose that we need to get the factorial of 5 which is denoted by 5!.

5! = 5 * 4 * 3 * 1 

Which is equals to 120. However if we need to find the factorial of 0 then it is always 1.

0! = 1

Now let us start with different method of getting factorial.

Method 1: Loop – Get factorial with JavaScript

function factorial(x){
  var ans = 1;
  for(var i=2; i<=x; i++){
    ans = ans * i;
  }
  return ans;
}
console.log(factorial(5));
//120

In the above code I am using a very popular method in JavaScript called loop . I simply run a loop starting from 2 till the end of given number in parameter. The reason I started from 2 is because either 1! or 0! both gives us same result which is 1. So I started with 2 in the loop. I simply multiply in each iteration to recursive multiplication. After that I return the after the end of loop which simply return the total factorial of given number in parameter.

Method 2: Logic – Get Factorial with JavaScript

function factorial(x) 
{ 
  if (x === 0)
 {
    return 1;
 }
  return x * factorial(x-1);         
}
console.log(factorial(5));
// 120

Method 3: High end Array Methods

function getFactorial(num){
  var factorial = 1;   var arr = [];
  
  if(num === 0) 
    return factorial;
  
  for(var i=1; i<=num; i++) {
    arr.push(i);  
  }
  
  factorial = arr.reduce((acc, val) => acc * val);
  return factorial;
  
}
console.log(getFactorial(10));
// 3628800

This method is only applicable if you have series of number in an array format. If you do not have array then you need to create one like I did with array method push. Also make sure you do no have 0 in the first place of array. If you have then you need to use splice method to pop out before using reduce method. Below script will help you to get rid of 0 if it is placed first in any array.

var arr = [0,1,2,3,4,5]
arr.splice(0,1);

This will give you 0 free array if you have 0 in the first place.

Santosh Shah

I am a JavaScript developer having enthusiasm on most frontend skills like JavaScript, HTML, CSS, SASS, node, gulp, angular etc. I love exploring new techniques and like to learn new technologies to keep my self up to date.


Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.