PUBLISHED ON: MARCH 14, 2023
JavaScript Program to Find the Factorial of a Number
Factorials are commonly used in mathematics and have a wide range of applications in various fields.
In this project, we will develop a JavaScript program to find the factorial of a given number. The program will take an input number and use a series of steps and calculations to determine the factorial value. We will utilize various features of the JavaScript programming language, such as loops and mathematical operators, to create a program that is efficient, accurate, and easy to understand. We also have an interactive JavaScript course where you can learn JavaScript from basics to advanced and get certified. Check out the course and learn more from here.
What is a Factorial Number
The factorial of a non-negative integer is the multiplication of all positive integers smaller than or equal to n.
For example factorial of 5 is 5*4*3*2*1 which is 120.
Factorial of n is given as n! = n * (n-1) * ... * 3 * 2 * 1
Note:
- The Factorial of 0 is said to be 1.
- The Factorial of negative numbers does not exist.
Program Approach
In the program given below the user is prompted to give an integer. Then we need to check whether the number is feasible to have a Factorial value.
- When the user enters a positive integer, a for loop is used to iterate over 1 to the number entered by the user to find the factorial.
- Each number is multiplied and stored in the factor variable.
Program to Find the Factorial of a Number
// JavaScript program to find the factorial of a number
const num = parseInt(prompt('Enter an integer: '));
// checking the non-feasibility of the numbers
if (num === 0)
console.log(`The factorial of ${number} is 1.`);
else if (num < 0)
console.log('Factorial for negative number does not exist.');
else {
var facto = 1;
for (var i = 1; i < number+1; i++) {
facto *= i;
}
console.log(`The factorial of ${num} is ${facto}.`);
}
Enter an integer: 6
The factorial of 6 is 720.
Conclusion
In conclusion, the JavaScript program that was made to find the factorial of a given number has proven to be a good way to figure out the factorial of any non-negative integer. The program uses a loop to go through all the numbers from 1 to the number entered and multiply each number by the factorial of the number before it. This process keeps going until the number given, at which point the program gives back the factorial value.
Overall, the program is a reliable and efficient way to figure out the factorial of a given number, and it could be used in a wide range of fields for a variety of purposes.