Recursion in JavaScript with Examples

A function can refer to and call itself.
A function that calls itself is called a recursive function.
There are three ways for a function to refer to itself:
The function’s name arguments.callee An in-scope variable that refers to the function
In some ways, recursion is analogous to a loop.
It is possible to convert any recursive algorithm to a non-recursive one, but the logic is often much more complex, and doing so requires the use of a stack.
In fact, recursion itself uses a stack: the function stack.
* * *
/ / The stack-like behavior can be seen in the
following example:
function foo(i) {
if (i< 0)
return;
console. log( ‘begin : ‘ + i);
foo(i – 1);
console.log( ‘end: ‘ + i);
}
foo(3);
// Output:
/ / begin: 3
/ / begin: 2
/ / begin: 1
/ / begin: 0
/ / end: 0
/ /end:1
/ / end: 2
/ / end: 3