Reputation: 105
Given this code:
function foo()
{
if (!foo)
{
//blah blah blah some code here
foo = true;
}
}
What exactly does this do? Why is it not creating a recursive call?
Upvotes: 0
Views: 107
Reputation: 382150
This might create a recursion :
function foo()
{
if (!foo()) // <=== notice the ()
{
//blah blah blah some code here
foo = true;
}
}
But there, without the parenthesis, foo
isn't executed. The tests only checks the variable foo
doesn't evaluate as true, and then replaces it with the boolean true
. It's a weird code but not a recursion.
Note that we're not sure, inside the function, that foo
is the function, as the code could be like this :
function foo() {
if (!foo)
{
//blah blah blah some code here
foo = true;
}
}
var f = foo;
foo = 0;
f(); // this would result in foo being true
Upvotes: 3
Reputation: 25728
Its not calling itself, just checking to see that a variable by that name exists/ is truthy. The function could be renamed and foo could refer to something else completely by the time it is called.
So to be clear, recursion occurs when a function calls itself
function foo(){
foo();
}
whereas what you're doing is just looking up the current value of foo without attempting to call it.
!foo //if foo is defined as a function or other truthy object, is true
Upvotes: 0