Javascript Program to find Factorial of a number

In this Javascript programming example we will cover how to find factorial of a given number. We know that Factorial is a product of number from 1 to given number.

A simple factorial of 0 is always 1.

Syntax of Factorial

Factorial of number x is x (x!)=1*2*.....x;

Let's write a simple Javascript program to find a factorial of a given number.

// Let take input number from the user
const num = parseInt(prompt('Enter a number: '));
// check given number os less than 0
if (num < 0) {
console.log('Only positive numbers are allowed');
}
// check if input = 0
else if (num == 0) {
console.log(`The factorial of ${num} is 1.`);
}
// check if input > 0
else {
let fact = 1;
for (x = 1; x <= num; x++) {
fact *= x;
}
P a g e | 22
console.log(`The factorial of ${num} is ${fact}.`);
}

 

Output:

Enter a number : 5

The factorial of 5 is 120

Subscribe For Daily Updates

100+ Python Pattern Examplespython pattern examples - star patterns, number patterns