You are currently viewing Factorial Function JavaScript Using For loop

Factorial Function JavaScript Using For loop

Factorial Function Javascript

In this article, I would like to discuss how to create a factorial function in javascript. First, we understand how to find the factorial of a given number,

If I want to find the factorial of 5 then I will find “5x4x3x2x1”. So, let’s see how to find the factorial of 5 in a javascript program.

Program

var num=5;
var fact=1;
for (var i = num; i >= 1; i--) {
fact=fact*i;
}
document.write(fact);
/* 
output:
120
*/

Steps:

  1. In the above code, we created a variable “num” and gave a value of 5. Because we are finding the factorial of 5, so we have given the value 5 for variable “num”.You must give the value of the number for which you want to find the factorial.
  2. Then we have variable “fact” and given the value 1. Because every factorial number ends in 1.
  3. Then we created a “reverse for loop” within that we assigned the variable “fact=fact*i“.
  4. And print the variable fact. See the above output, the factorial number of 5 is displayed as 120 successfully.

Leave a Reply