Your question is this:
Why sometimes defining variable after calling the variable doesn't
give undefined?
Then you provide this as example:
alert(i); // alert undefined
var i = 1;
It alerts undefined
because you are issuing the alert()
before i
is defined.
And in the first example:
function sayAlice() {
var sayAlert = function() { alert(alice); }
var alice = 'Hello Alice';
return sayAlert;
}
sayAlice()() //alert Hello Alice
The same behavior is to be expected, but it seems like your odd way of calling sayAlice
happens twice with that ()()
. Which basically means while it might be happening quickly, but the first call to sayAlice()
will set the alice
variable, but the alert
is most likely happening on the second iteration called via sayAlice()()
.
Wait. Looking at it again, this is what is happening in the first example. This simply defines sayAlert
as a function but does not actually run it:
var sayAlert = function() { alert(alice); }
But then you do this:
var alice = 'Hello Alice';
Which assigns a value to alice
. And then you finally do this:
return sayAlert;
Which happens after the first two items. Meaning, at that third line you have a function defined, and then a variable defined, but it only comes together in the final line.
Which makes sense to me. But sayAlice()()
with the double ()
seems odd.