I\'ve been reading about JavaScript hoisting sometime back.
JavaScript Scoping and Hoisting by Ben Cherry
Two words about “hoisting” by Dmitry Soshnikov
For your example number 1, the alert is shown because you're using var
inside the function and the var
declaration is hoisted to the top of the function, so it is equivalent to:
var foo = 1;
function bar() {
var foo;
if (!foo) {
alert('inside if');
foo = 10;
}
}
bar();
One might conclude that these sorts of issues offer compelling reason to declare all variables explicitly at the top of the function.
Only variable declaration is eagerly evaluated. The variable assignment in your first case (in the if
block) occurs only upon entering the if
block.
The variable you only declare, but not assign any value to, has the value of undefined
(which coerces to false
).