JavaScript(JS) JS find the factorial of a number
In JavaScript, you can find the factorial of a number using a loop. Here's an example:
function factorial(num) { let result = 1; for (let i = 2; i <= num; i++) { result *= i; } return result; } console.log(factorial(5)); // Output: 120oSurce:www.theitroad.com
In the above example, we define a function called factorial
that takes a number num
as its argument. We initialize a variable called result
to 1
and use a for
loop to multiply result
by the integers from 2
up to num
. Once the loop finishes, we return the final value of result
, which is the factorial of num
.
We then call the factorial
function with an argument of 5
, which calculates the factorial of 5
using a loop and returns the value 120
. You can replace the value of the argument with any other number to calculate its factorial using a loop.