# JavaScript: Recursion

Recursion is a technique, where a Function can call itself. For example, following function calculates the factorial of a number using recursion.

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

There are three ways that a function can refer to itself.
a.   By using function name
b.   By using arguments.callee
c.   By using an in-scope variable that refers to the function

By using function name
function factorial_1(n){
if(n
return 1;
return n * factorial_1(n-1);
}

By using arguments.callee
function factorial_2(n){
if(n
return 1;
return n * arguments.callee(n-1);
}

By using an in-scope variable that refers to the function
var factorial_3 = function factorial(n){
if(n
return 1;
return n * factorial_3(n-1);
}

factorial.html
`Factorial"text/javascript">// By using function name function factorial_1(n) {if (n  2)return 1;return n * factorial_1(n - 1);        }// By using argument.calleefunction factorial_2(n) {if (n  2)return 1;return n * arguments.callee(n - 1);        }// By using in-scope variablevar factorial_3 = function factorial(n) {if (n  2)return 1;return n * factorial_3(n - 1);        }document.write("Factorial of 5 is " + factorial_1(5) + "");document.write("Factorial of 10 is " + factorial_2(10) + "");document.write("Factorial of 20 is " + factorial_3(20) + "");`

Open above page in browser, you can able to see following text.

Factorial of 5 is 120
Factorial of 10 is 3628800
Factorial of 20 is 2432902008176640000

Previous                                                 Next                                                 Home

This post first appeared on Java Tutorial : Blog To Learn Java Programming, please read the originial post: here

# Share the post

JavaScript: Recursion

×