Factorial of number

Using javascript you can find factorial of any number, here same logic are applied like c language
you only need to write your javascript code inside <script> ..... </script> tag using any editor like notepad or edit plus. Save below code with .html or .htm extension. No need to compile your javascript code just open your code in any web browser.

Find factorial of number using JavaScript

Example Factorial of any number

<!doctype html>
<html>
<head>
<script>
function show(){

var i, no, fact;
fact=1;
no=Number(document.getElementById("num").value);
for(i=1; i<=no; i++)  
{
fact= fact*i;
}  
document.getElementById("answer").value= fact;
}
</script>
</head>
<body>
Enter Num: <input id="num">
<button onclick="show()">Factorial</button>
<input id="answer">
</body>
</html>

Result

Enter Num:   

Code Explanation

  • no=Number(document.getElementById("num").value);
    This code is used for receive input value form input field which have id num.
  • document.getElementById("answer").value= fact;
    This code is used for receive calculated value of factorial and display in input field which have id answer
  • <button onclick="show()">Factorial</button>
    This code is used for call show function when button clicked.