Recursion
I often see the term "recursion" used when a function repeated calls itself, though what is the unambiguous definition of "recursion" in JavaScript?
That definition seems fine, but the function doesn't have to call itself directly to be recursive, it's execution just has to lead to it being called again. An example of recursion where the function doesn't directly call itself is: Calling A();
calls B();
which calls C();
which calls A();
again.
Repeated Scheduling
A function like this uses repeated scheduling:
function A ( foo ) {
var bar;
setTimeout( A, 0 );
console.log( 'hello' );
}
It is not recursive because A isn't called repeatedly on the same call stack. When the current call stack is done (which means 'hello' will have been logged) and nothing else is ahead of calling A again in the event loop, A will be called. Aside from the difference between synchronous and asynchronous code, the important different here is that there is only ever one copy of foo
and bar
at a time, and the call stack isn't growing, hence there will be no memory or Maximum call stack size exceeded errors, which there would be for this version which uses recursion:
function A ( foo ) {
var bar;
A();
console.log( 'hello' );
}
In that case 'hello' will never be printed since A
calls itself before it gets to the logging statement.
A Non-Terminating Procedure that Refers to Itself
A non-terminating procedure is just an infinite loop. Referring to itself is somewhat meaningless:
function A ( ) {
// Never terminates
while ( true ) {
// If A() is called here, or before
// the loop you have infinite
// recursion and a stack size error
}
// If, instead, A() is called here,
// you just have an infinite-loop,
// since this statement is never reached
}