My Development Notes

Programming Made Easier


Factorial of a given number in JavaScript

Factorial of an integer ‘n’ is represented by ‘n!’. Factorial of an integer n is the product of all positive integers less than or equal to n. Examples :

// 5! = 5 * 4 * 3 * 2 * 1 = 120
// 7! = 7 * 6 * 5 * 4 * 3 * 2 * 1 = 5040

Here’s a way to find the factorial of a given number:

function factorialInt(num) {
  let factInt = 1;
  for (let i = 2; i <= num; i++) {
    factInt *= i;
  }
  return factInt;
}

factorialInt(7);

// returns 5040 to the console

Here the variable factInt is initialized at 1 since the function will always be greater than or equal to 1, why? because even 0! = 1. So, if we input 0, the for loop condition will become false and not execute and factInt will remain 1.

For all other positive integers, each factInt increment gets multiplied up to the value of num and then the loop breaks because we’ve used a simple for loop. This returns the factorial of a given number.

Next we’ll use the recursive function to find the factorial of 7:

function factInt(num) {
  if (num === 0) {
    return 1;
  }
  return num * factInt(num - 1);
}

factInt(4);

// returns 24

What we’ve done in the above code is that we’ve used a recursion, which is like a function running inside a function. So, if num = 0 it returns 1. If it’s anything above that, the recursion keeps running until factInt = 0 in num * factInt(num-1) where it stops.

Understand this visually with the code breakdown below :

4 * factInt(4-1) 
then 4*3*factInt(3-1)
then 4*3*2*factInt(2-1)
then 4*3*2*1*factInt(1-1)
then 4*3*2*1*factInt(0)  // factInt(0) = 1 as per the function
So, finally 4*3*2*1*1 = 24

Posted

in

by

Tags:

Leave a Reply