Writing a For Loop to Evaluate a Factorial - JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

We are required to write a simple JavaScript function that takes in a Number, say n and computes its factorial using a for loop and returns the factorial.

For example −

factorial(5) = 120,
factorial(6) = 720

Maintain a count and a result variable, keep multiplying the count into result, simultaneously decreasing the count by 1, until it reaches 1

And then finally we return the result.

Example

Following is the code −

const num = 14;
const factorial = num => {
   let res = 1;
   for(let i = num; i > 1; i--){
      res *= i;
   };
   return res;
};
console.log(factorial(num));

Output

This will produce the following output in console −

87178291200
raja
Published on 18-Sep-2020 13:34:47
Advertisements