settingsAccountsettings
Menusettings

Q: Calculate Factorial of a number in JavaScript

+5 votes

How to write a script/program to calculate factorial of a particular number in JavaScript? Should I use for loop? Or reverse for loop?

asked in JavaScript category by user john7

2 Answers

+5 votes

This is the solution with the for loop - has no issues with factorial of 0 - which is the number 1:

function factorial(num) {
    var result = 1;
    for (var i = 2; i <= num; i++) {
        result *= i;
    }
    return result;
}

 

answered by user Jolie Ann
Thanks! Useful and working! :-)
+3 votes

Here is the solution with the reverse for loop (with some modifications with the number 0):

function factorial(num) {
    if (num === 0) {
        return 1;
    }
    var result = num;
    for (var i = num - 1; i >= 1; i--) {
        result *= i;
    }
    return result;
}

 

answered by user matthew44
...