- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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