Skip to content

How to make a Javascript Factorial Function?

I want to write a factorial function in javascript. I have tried the following:

function factorial(n){
  if(n==1){
    return 1;
  } else {
   while(n>=0){
    n = n * (n-1);
   }
   return n;
 }
}

It is not working.

Answer

You used while(n>=0) instead of while(n>=2). Using n>=0 will make the end of the while loop multiply n by 0. You should also use the === operator to prevent values that are not numeric. You also forgot to decrease n in the while loop. Try one of the following:

Iteration method:

function factorial(n){
 var result = n;
 if(n<0){
   return null;
 }
 if(n===1||n===0){
return 1;
 } else {
 while(n>=2){
 result = result * (n-1); 
 n--;
}
return result;
}
}

<script>
 function factorial(n){
     var result = n;
     if(n<0){
       return null;
     }
     if(n===1||n===0){
    return 1;
     } else {
     while(n>=2){
     result = result * (n-1); 
     n--;
    }
    return result;
    }
    }
function calculate(){
   var input = document.getElementById("number").value;
   if(!isNaN(input)&&input.trim().length){
    document.getElementById("result").innerHTML = factorial(parseInt(input, 10));
   } else {
    document.getElementById("result").innerHTML = "<b style='color: red;'>Input must be a number!</b>";
   }
}
</script>
<input type="text" id="number" onkeyup="calculate()">
<br/>
<span id="result"></span>

Recursive method:

function factorial(n){
 if(n===0||n===1){
   return 1;
 }
 return n*factorial(n-1);
}