DEV Community

Cover image for Factorial Function in JavaScript - Quick Explanation.
Jessica-Agorye
Jessica-Agorye

Posted on

Factorial Function in JavaScript - Quick Explanation.

Factorial is a mathematical formula that multiplies a number by every number below it down to one.

when you see this code example,

function factorial(n) {
if (n == 0) {
return 1;
} else {
return factorial(n - 1) * n;
}
13
}
console.log(factorial(8));
// → 40320

Here's how it's solved

  • if n is 0, it returns 1 and ends the condition for recursion, else
  • if n is not 0, it calls itself with n-1 multiplied by n

Finding factorial(8)

factorial(n - 1) * n

n becomes 8 - we can say that 8 is the argument that is passed to the factorial function

factorial (n-1)*n

is simply

(8-1) * 8

which becomes

factorial (7 )* 8

First, find the factorial of 7 then multiply the result by 8

7! is 7x6x5x4x3x2x1 - which equals to 5040

Multiply the result of the factorial of 7 by 8

5040 * 8 equals 40320

Finir!

Top comments (0)

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More