DEV Community

Cover image for Factorial In Javascript
Margarita Vlachou
Margarita Vlachou

Posted on

Factorial In Javascript

Factorial Formula

The factorial function (symbol: !) says to multiply all whole numbers from our chosen number down to 1.

Alt Text

In general the formula has as shown below:

n! = n * (n-1) * (n-2) * .... * 2 * 1

If for example we would like to calculate the factorial of number 4 then we would have:

4! = 4 * 3 * 2 * 1

Factorial in Javascript

Here's how we would calculate the factorial in Javascript

function FirstFactorial(num) {     //consider our num=3
factorial = 1;
for (var i=1; i<=num; i++){        // loop from 1 to 3
  factorial *= i;                  // and multiply with each number
} 

 return factorial;                 //return the factorial which is 
                                   // 3*2*1=6

}
Enter fullscreen mode Exit fullscreen mode

Top comments (1)

Collapse
 
uzoafrica profile image
Ibezim Uzome Joseph

Clean and simply explained. Hello Margarita Vlachou please chat me on Instagram #Uzoafrica. I have a job on factorial and i need your assistance. Thanks