# factorial program in javascript

## Factorial Program in JavaScript

### Introduction

In mathematics, factorial of a non-negative integer n is denoted by n!. It is the product of all positive integers less than or equal to n. For example, the factorial of 5 is 5 x 4 x 3 x 2 x 1 = 120. In this article, we will see how to write a factorial program in JavaScript.

### Program

Here's a simple program to calculate the factorial of a number using a for loop:


function calculateFactorial(number) {
let result = 1;
for (let i = 2; i <= number; i++) {
result *= i;
}
return result;
}


Let's go through the code step by step:

• First, we define a function named "calculateFactorial" that takes a single argument "number".
• We create a variable named "result" and set its value to 1. This variable will hold the final result of our program.
• We then start a for loop that will iterate from 2 to the input number "number".
• Inside the loop, we multiply the current value of "result" with the loop variable "i".
• Finally, we return the value of "result" after the loop has completed.

To test our program, we can call the function with any non-negative integer as its argument. For example:


calculateFactorial(5); // returns 120
calculateFactorial(10); // returns 3628800
calculateFactorial(0); // returns 1 (by definition)


### Alternative Program using Recursion

Another way to write a factorial program in JavaScript is using recursion. Here's the code for it:


function calculateFactorial(number) {
if (number <= 1) {
return 1;
} else {
return number * calculateFactorial(number - 1);
}
}


This program calculates the factorial of a number by calling itself recursively. Here's how it works:

• First, we define a function named "calculateFactorial" that takes a single argument "number".
• We check if the input number is less than or equal to 1. If it is, we return 1 (by definition, the factorial of 0 and 1 is 1).
• Otherwise, we return the product of the input number "number" and the factorial of (number - 1).
• This recursive call continues until the base case is reached (i.e. when number is 1 or 0).

To test our program, we can call the function with any non-negative integer as its argument. For example:


calculateFactorial(5); // returns 120
calculateFactorial(10); // returns 3628800
calculateFactorial(0); // returns 1 (by definition)


### Conclusion

In this article, we saw two ways to write a factorial program in JavaScript. The first method uses a for loop, while the second method uses recursion. Both methods are valid and produce the same result. The choice of method depends on personal preference and the specific requirements of the program.

### Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe