Factorial of a Number
Program to calculate factorial of a number
JavaScript Factorial of a Number Program
This program helps you to learn the fundamental structure and syntax of JavaScript programming.
// Factorial: n! = n × (n-1) × (n-2) × ... × 2 × 1
// Example: 5! = 5 × 4 × 3 × 2 × 1 = 120
// Method 1: Using for loop
function factorialLoop(n) {
if (n < 0) return "Invalid input";
if (n === 0 || n === 1) return 1;
let result = 1;
for (let i = 2; i <= n; i++) {
result *= i;
}
return result;
}
console.log("5! =", factorialLoop(5));
console.log("0! =", factorialLoop(0));
console.log("10! =", factorialLoop(10));
// Method 2: Using recursion
function factorialRecursive(n) {
if (n < 0) return "Invalid input";
if (n === 0 || n === 1) return 1;
return n * factorialRecursive(n - 1);
}
console.log("\nUsing recursion:");
console.log("5! =", factorialRecursive(5));
console.log("7! =", factorialRecursive(7));
// Method 3: Using while loop
function factorialWhile(n) {
if (n < 0) return "Invalid input";
if (n === 0 || n === 1) return 1;
let result = 1;
let i = n;
while (i > 1) {
result *= i;
i--;
}
return result;
}
console.log("\nUsing while:");
console.log("6! =", factorialWhile(6));
// Method 4: Using reduce
function factorialReduce(n) {
if (n < 0) return "Invalid input";
if (n === 0 || n === 1) return 1;
return Array.from({length: n}, (_, i) => i + 1)
.reduce((product, num) => product * num, 1);
}
console.log("\nUsing reduce:");
console.log("4! =", factorialReduce(4));5! = 120 0! = 1 10! = 3628800 Using recursion: 5! = 120 7! = 5040 Using while: 6! = 720 Using reduce: 4! = 24
Understanding Factorial of a Number
This program demonstrates different approaches to calculate factorial.
Factorial Definition
n! = n × (n-1) × (n-2) × ... × 2 × 1
Special Cases:
Method 1: For Loop
Iterative approach:
let result = 1;
for (let i = 2; i <= n; i++) {
result *= i;
}
Pros:
Method 2: Recursion
Function calls itself:
function factorial(n) {
if (n <= 1) return 1;
}
return n * factorial(n - 1);How Recursion Works:
Example: factorial(5)
Pros:
Cons:
Method 3: While Loop
Decrementing counter:
while (i > 1) {
result *= i;
i--;
}
Method 4: Reduce (Functional)
Using array methods:
Array.from({length: n}, (_, i) => i + 1)
.reduce((product, num) => product * num, 1);
Edge Cases:
When to Use:
-
Loop
: Production code, large numbers
-
Recursion
: Learning, small numbers
-
Reduce
: Functional style
Let us now understand every line and the components of the above program.
Note: To write and run JavaScript programs, you need to set up the local environment on your computer. Refer to the complete article Setting up JavaScript Development Environment. If you do not want to set up the local environment on your computer, you can also use online IDE to write and run your JavaScript programs.