My sample code:
var foo = 1;
function bar() {
foo = 10;
return;
function foo() {}
}
bar();
alert(foo);
Why does it alert 1? I am expecting 10. However if I comment out function foo(){} after return, it does return 10.
My sample code:
var foo = 1;
function bar() {
foo = 10;
return;
function foo() {}
}
bar();
alert(foo);
Why does it alert 1? I am expecting 10. However if I comment out function foo(){} after return, it does return 10.
Function declarations inside other functions are treated as if they appeared at the very start of the containing function. That is, your bar()
function is treated as if it looked like:
function bar() {
function foo() {}
foo = 10;
return;
}
Thus foo
is a local symbol in the function, and assignment to it does not affect the global foo
.