JavaScript

How to find factorial of a number in JavaScript

Factorial is the product of all integers between 1 and itself. There are three ways to find a factorial of a given number, using the for loop, recursion, or creating a function in a range from 1 to X (the number entered by the user). Example:

0! = 1
1! = 1
2! = 2 * 1
3! = 3 * 2 * 1
4! = 4 * 3 * 2 * 1
5! = 5 * 4 * 3 * 2 * 1
6! = 6 * 5 * 4 * 3 * 2 * 1
 

Factorial program in javascript using for loop
function fact(nbr){
	var i, nbr, f = 1;

	for(i = 1; i <= nbr; i++)  
	{
		f = f * i;   // or f *= i;
	}  
  return f;
}

console.log(fact(3));

Output:

6

 

Factorial program in javascript using recursion
function fact(nbr) 
{
  if (nbr === 0)
  {
     return 1;
  }
  return nbr * fact(nbr-1);
}

console.log(fact(3));

Output:

6
mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

Your email address will not be published. Required fields are marked *