Recursive functions
A function that calls itself during an execution is called a Recursive function.
function recurseFn() {
recurseFn();
}
recurseFn();
recurseFn()
is a recursive function, which calls itself inside the function.
Working flow of recursion in JavaScript
function factorial(n) {
if (n === 0) return 1;
else return n * factorial(n - 1);
}
console.log(factorial(5));
To find factorial, we are using the recursive function which repeated calls factorial(n - 1) until the if condition is true. When if condition is true the loop is excited by using break statement.
Note
While using the recursive function, it is better to use the if statement to avoid logical issues because sometimes there is a chance for getting some error.