A variable’s declaration is hoisted, but not its definition. So your second example is equivalent to:
function myFunction() {
var myInternalFunction
myInternalFunction = function() {
return "Hello World."
}
return myInternalFunction()
myInternalFunction = function() {
return "Second Definition."
}
}
Here it becomes obvious that the myInternalFunction
is unreachable, so the first definition is used as it is the value of myInternalFunction
at the time it’s called. JSLint correctly complains (using your original code):
Unreachable var
after return
.
Compare with your first example, where the function declarations are hoisted, so your code is equivalent to:
function myFunction() {
function myInternalFunction() {
return 10
}
function myInternalFunction() {
return 20
}
return myInternalFunction()
}
As we can see here, myInternalFunction
is immediately redeclared, and so the last one wins. Both declarations happen before calling the function itself.
So, why this expressions alert lastly called variable:
var a = "one";
var a = "two";
alert(a); // alerts two ???? shouldn't be "one" if expressions?
This isn’t equivalent to your function example; an equivalent example would be:
var a = "one"
alert(a)
var a = "two"
And expected it to alert “two”. I think it’s obvious it won’t. The value of the variable, be it function, string, or anything else, is not relevant.