To find the factorial of a number in JavaScript, you can use either recursive function or loop.
Using Recursive Function:
index.tsx181 chars12 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.tsx255 chars16 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