Find Factorial of a number using only JavaScript!

JavaScript is one of mostly used scripting language all over the world. Today in this post we are going to see how to write a program to print Factorial values of a number using plain JavaScript.

Lets’ see the example (Find Factorial of a number using JavaScript):

<!DOCTYPE Html>
<html>
<head>
<title>Find factorial of a number using Javascript</title>
<script type="text/javascript">
	function findFactorial(){
		//clear the result div
        document.getElementById("result").innerHTML = "";
		var num = document.getElementById("number").value;
		var fact = 1;
		
		//loop till the iterator i equals to number
		for (i = 1; i <= num; i++){

			//formula to calculate factorial is to 
			//multiply the iterator i value with fact value.			
			fact = fact * i;

			//put the below lines of code out of this 'for loop' to show only the total value
            document.getElementById("result").insertAdjacentHTML('beforeend', '<br>');
			document.getElementById("result").insertAdjacentHTML('beforeend', fact);
		}
	}
</script>
</head>
<body>
	<h2>Find factorial of a number using Javascript</h2>
	Enter Number: <input type="number" id="number" min="1" max="100" /><button onclick="findFactorial()">Calculate</button>
	<div id="result"></div>
</body>
</html>

Output of the above program will be something like this:

javascriptfactorial

You can see the demo of the above script here:

demo

 

Leave a Comment

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

Scroll to Top