Computer >> Computer tutorials >  >> Programming >> Javascript

Function to compute factorial of a number in JavaScript


We are required to write a simple JavaScript function that takes in a Number, say n and computes its factorial.

Maintain a count and a result variable. We will keep multiplying the count into result and simultaneously decreasing the count by 1, until it reaches 1.

And then finally we return the result.

Therefore, let’s write the code for this function −

Example

The code for this will be −

const num = 14;
const factorial = num => {
   let res = 1;
   for(let i = num; i > 1; i--){
      res *= i;
   };
   return res;
};
console.log(factorial(num));

Output

The output in the console will be −

87178291200