JavaScript(JS) JS find factorial of number using recursion
In JavaScript, you can find the factorial of a number using recursion. Here's an example:
function factorial(num) { if (num === 0 || num === 1) { return 1; } else { return num * factorial(num - 1); } } console.log(factorial(5)); // Output: 120Soucre:www.theitroad.com
In the above example, we define a function called factorial
that takes a number num
as its argument. If num
is equal to 0
or 1
, the function returns 1
. Otherwise, the function returns num
multiplied by the result of calling factorial(num - 1)
. This recursive call continues until num
is equal to 0
or 1
, at which point the function returns 1
.
We then call the factorial
function with an argument of 5
, which calculates the factorial of 5
using recursion and returns the value 120
. You can replace the value of the argument with any other number to calculate its factorial using recursion.