Factorial of a Number using Recursion Function
In this tutorial, you are given a number. Write a JavaScript program with a function that takes a number as argument, find the factorial of the number using recursion function, and returns the result.
Solution
Create a function findFactorial()
that takes n
as argument.
If n
is 0
or 1
, the function returns 1
, else the function returns n * findFactorial(n - 1)
. The function calls itself, findFactorial()
, hence a recursive function.
Program
In the following program, we find the factorial of a number in n
using recursion function.
function findFactorial(n) {
if (n == 0 || n == 1) {
return 1;
}
return n * findFactorial(n - 1);
}
var n = 5;
console.log(n+'! = '+ findFactorial(n));