find the factorial of a number in javascript

To find the factorial of a number in JavaScript, you can use either recursive function or loop.

Using Recursive Function:

index.tsx
function factorial(num) {
    if (num < 0) {
        return -1;
    }
    else if (num == 0) {
        return 1;
    }
    else {
        return (num * factorial(num - 1));
    }
}
181 chars
12 lines

Here, we are using a recursive function to calculate the factorial of the given number. If the number is negative then we return -1, if the number is 0 then we return 1, otherwise we return the product of that number and recursive call to the function with num-1 as argument.

Using Loop:

index.tsx
function factorial(num) {
    if (num < 0) {
        return -1;
    }
    else if (num == 0) {
        return 1;
    }
    else {
        var fact = 1;
        for (var i = 1; i <= num; i++) {
            fact *= i;
        }
        return fact;
    }
}
255 chars
16 lines

Here, we are using a loop to calculate the factorial of the given number. We initialize the variable ‘fact’ with 1 and then run a loop from 1 till the given number. In each iteration we multiply the fact variable by the current iteration number. Finally, we return the fact variable.

gistlibby LogSnag