0
0
JavascriptProgramBeginner · 2 min read

JavaScript Program to Find Factorial of a Number

You can find the factorial of a number in JavaScript by using a loop like for (let i = 1; i <= n; i++) result *= i; where result starts at 1 and n is the input number.
📋

Examples

Input0
Output1
Input5
Output120
Input1
Output1
🧠

How to Think About It

To find the factorial of a number, multiply all whole numbers from 1 up to that number. Start with 1 because multiplying by 1 does not change the value. Then multiply by 2, then 3, and so on until you reach the number itself.
📐

Algorithm

1
Get the input number n.
2
Set a variable result to 1 to hold the factorial value.
3
For each number i from 1 to n, multiply result by i.
4
After the loop ends, return the result.
💻

Code

javascript
function factorial(n) {
  let result = 1;
  for (let i = 1; i <= n; i++) {
    result *= i;
  }
  return result;
}

console.log(factorial(5));
Output
120
🔍

Dry Run

Let's trace factorial(5) through the code

1

Initialize result

result = 1

2

Multiply by 1

result = 1 * 1 = 1

3

Multiply by 2

result = 1 * 2 = 2

4

Multiply by 3

result = 2 * 3 = 6

5

Multiply by 4

result = 6 * 4 = 24

6

Multiply by 5

result = 24 * 5 = 120

7

Return result

return 120

iresult
11
22
36
424
5120
💡

Why This Works

Step 1: Start with 1

We start with result = 1 because multiplying by 1 does not change the value and it is the identity for multiplication.

Step 2: Multiply step-by-step

We multiply result by each number from 1 up to n to build the factorial product.

Step 3: Return final product

After the loop finishes, result holds the factorial value, which we return.

🔄

Alternative Approaches

Recursive function
javascript
function factorial(n) {
  if (n === 0) return 1;
  return n * factorial(n - 1);
}

console.log(factorial(5));
Uses function calling itself; elegant but can cause stack overflow for very large n.
Using Array.reduce
javascript
function factorial(n) {
  if (n === 0) return 1;
  return Array.from({ length: n }, (_, i) => i + 1).reduce((acc, val) => acc * val, 1);
}

console.log(factorial(5));
Uses array and reduce method; more functional style but less efficient for large n.

Complexity: O(n) time, O(1) space

Time Complexity

The loop runs from 1 to n, so the time grows linearly with n, making it O(n).

Space Complexity

Only a few variables are used regardless of input size, so space is O(1).

Which Approach is Fastest?

The iterative loop method is fastest and uses least memory compared to recursion or array methods.

ApproachTimeSpaceBest For
Iterative loopO(n)O(1)General use, large inputs
Recursive functionO(n)O(n)Simple code, small inputs
Array.reduceO(n)O(n)Functional style, readability
💡
Remember factorial of 0 is always 1 by definition.
⚠️
Beginners often forget to start multiplication from 1 or handle the case when input is 0.