Finding Factorial of a Number with JavaScript

First of all we must understand the meaning of factorial:

The factorial function multiply all numbers from our chosen number down to 1.

For instance:

  • 3! = 3 x 2! = 3 x 2 x 1 = 6
  • 5! = 5 x 4! = 5 x 4 x 3 x 2 x 1 = 120
  • 1! = 1
  • 0! = 1

Way of thinking:

  • We need a recursive function to calculate multiply of ordered numbers.
  • We must return 1 when we get 0 and we must stop recursive function.
function factorial(num) {
  if(num <= 0) {
    return 1;
  } else {
    let result = num * factorial(num - 1)
    return result;
  }
}