Support us .Net Basics C# SQL ASP.NET Aarvi MVC Slides C# Programs Subscribe Download

### Recursive function in JavaScript

Suggested Videos
Part 27 - Closures in JavaScript
Part 28 - JavaScript closure example
Part 29 - JavaScript arguments object

Recursion is a programming concept that is applicable to all programming languages including JavaScript

What is a recursive function?
Recursive function is function that calls itself.

When writing recursive functions there must be a definite break condition, otherwise we risk creating infinite loops.

Example : Computing the factorial of a number without recursion

function factorial(n)
{
if (n == 0 || n == 1)
{
return 1;
}

var result = n;
while (n > 1)
{
result = result * (n - 1)
n = n - 1;
}

return result;

}

document.write(factorial(5));

Output : 120

Example : Computing the factorial of a number using a recursive function

function factorial(n)
{
if (n == 0 || n == 1)
{
return 1;
}
return n * factorial(n - 1);
}

document.write(factorial(5));

Output : 120 