Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
Selected Reading
Writing a For Loop to Evaluate a Factorial - JavaScript
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
Advertisements
