First up, an "empty" return;
statement simply exits the function at that point, returning undefined
. It is equivalent to return undefined;
.
The simple case, if you eliminate the function a(){}
part, is that the b()
function changes the global variable a
to be 10
, so then when you alert the value of a
after running the b()
function it is 10
. Without that inner function, all references to a
mean the global variable.
But with the function a(){}
part, that function is declared inside b()
. It is local to b()
. So then you have two different a
s: the global variable, and the local one in b()
. Regardless of where within the containing function another function statement appears, it is treated by the JS compiler as if it is at the top of the function. So even though the function a(){}
line is at the end of the containing b()
function in effect what happens when the code runs is the following:
var a = 1; // declare a global variable a
function b() {
function a() {} // declare a local function a
a = 10; // update local a to be 10 instead of a function
return;
}
b();
alert(a); // show value of global a, which is still 1