Recursive function in JavaScript




Link for all dot net and sql server video tutorial playlists
http://www.youtube.com/user/kudvenkat/playlists

Link for slides, code samples and text version of the video
http://csharp-video-tutorials.blogspot.com/2015/01/recursive-function-in-javascript.html

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

Original source