# JavaScript Program to Find Factorial of a Number

In this post, we will learn how to find the factorial of a number using JavaScript Programming language.

Factorial of a number is a function that multiplies every natural number less than that number. For example: Factorial of 3 is 3 x 2 x 1 = 6.

We will compute the factorial using a simple for loop function.

So, without further ado, letâ€™s begin this tutorial.

Contents

## JavaScript Program to Find Factorial of a Number

```// JavaScript Program to Find Factorial of a Number
var num = parseInt(prompt("Enter a positive integer: "));

// Checking if number is negative
if (num < 0){
console.log("Factorial of negative numbers doesn't exist.");
}

// Checking whether number equals to zero
else if (num == 0){
console.log("Factorial of 0 is: 1");
}

// Checking if number is positive
else{
let fact = 1;
for (i = 1; i <= num; ++i){
fact = fact * i;
}
console.log(`Factorial of \${num} is: \${fact}.`);
}
```

Output 1

``````Enter a positive integer: -5
Factorial of negative numbers doesn't exist.
``````

Output 2

``````Enter a positive integer: 0
Factorial of 0 is: 1
``````

Output 3

``````Enter a positive integer: 4
Factorial of 4 is: 24.
``````

## How Does This Program Work ?

```var num = parseInt(prompt("Enter a positive integer: "));
```

The user is asked to enter a positive integer.

```// Checking if number is negative
if (num < 0){
console.log("Factorial of negative numbers doesn't exist.");
}
```

If the entered number is less than 0, we display a message stating that the factorial of negative numbers doesnâ€™t exist.

```// Checking whether number equals to zero
else if (num == 0){
console.log("Factorial of 0 is: 1");
```

If the entered number is 0, then itâ€™s factorial will be 1.

```// Checking if number is positive
else{
let fact = 1;
for (i = 1; i <= num; ++i){
fact = fact * i;
}
console.log(`Factorial of \${num} is: \${fact}.`);
}
```

Now, we calculate the factorial of the positive integer using a for loop. The factorial gets stored in the fact named variable and is displayed on the screen using the console.log() statement.

## Conclusion

I hope after going through this post, you understand how to find the factorial of a number using JavaScript Programming language.

If you have any doubt regarding the program, feel free to contact us in the comment section. We will be delighted to help you.