Write a JavaScript program to find the factorial of a number
Description: Find the factorial of 5 in two ways: with a loop and with a recursive function.
Hint:
- Factorial of 5 is 5 x 4 x 3 x 2 x 1 = 120.
- A recursive function needs a base case.
JavaScript factorial program
// loop
let fact = 1;
for (let i = 1; i <= 5; i++) {
fact *= i;
}
console.log(fact);
// recursion
function factorial(n) {
if (n <= 1) return 1; // base case
return n * factorial(n - 1);
}
console.log(factorial(5));
Output:
Tutorials Class - Output Window
120
120
How it works
- The loop multiplies
factwith 1, 2, 3, 4 and 5. - The recursive function calls itself with a smaller number until it reaches the base case.
Read JavaScript Functions.
Learn more about the similar topics:
| Tutorials |
|---|
| No Content Found. |
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |