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

The approach is to maintain a count and a result variable, keep multiplying the count into result, simultaneously decreasing the count by 1, until it reaches 1. Then finally we return the result.

Syntax

function factorial(n) {
    let result = 1;
    for (let i = n; i > 1; i--) {
        result *= i;
    }
    return 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

How It Works

The factorial function works by:

  • Starting with res = 1 (multiplicative identity)
  • Using a for loop that counts down from num to 2
  • Multiplying each number into the result: res *= i
  • Returning the final accumulated product

Additional Examples

// Test with smaller numbers
console.log(factorial(5));  // 5! = 5 × 4 × 3 × 2 × 1
console.log(factorial(6));  // 6! = 6 × 5 × 4 × 3 × 2 × 1
console.log(factorial(0));  // Edge case: 0! = 1
console.log(factorial(1));  // Edge case: 1! = 1
120
720
1
1

Conclusion

The for loop approach provides an efficient iterative solution for calculating factorials. It avoids recursion overhead and works well for reasonable input sizes.

Updated on: 2026-03-15T23:18:59+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements