Indyarock

Creating Codes with Passion

Find out the factorial of a number (JavaScript)

Here is a JavaScript to calculate the factorial of number, given by a user:

The interface looks like this:
Screen Shot 2012-12-02 at 2.07.38 AM

And here is the code:

<!DOCTYPE html>
<html>
<body>

<p>Factorial: Enter the number and click calculate.</p>
X:<input id="x" value="1"/><br><br>
<button onclick="myFunction()">Calculate Factorial</button>
<p id="demo"></p>

<script>
function myFunction()
{
var x = document.getElementById("x").value
document.getElementById("demo").innerHTML="Factorial of " + x + " = " + fact(x);
}

function fact(x)
{
  if (x==1)
  {return 1;}
  else
  {return x*fact(x-1);}
}
</script>

</body>
</html>

Enjoy 😛

Leave a comment