Variable declarations are moved to the top of the scope they are defined in and the values are not assigned, till the assignment line is executed. So, your second code can be understood as
function a() {
var h = 1;
function b() {
var h;
if (false) {
h = h * 2;
}
alert(h);
}
b();
}
a();
Even though you have defined h
within the if
clause, since JavaScript doesn't have block scoping, the variable declaration is actually moved to the top of the function. And since the if
condition is not satisfied, h
is never assigned a value. That is why it alerts undefined