3
function a(){
    var h = 1;
    function b(){
        alert(h);
    }
    b();
}
a();

alerts 1;

function a(){
    var h = 1;
    function b(){
        if(false){
            var h = h * 2;
        }
        alert(h);
    }
    b();
}
a();

alerts undefined. Why ?

Rayjax
  • 7,494
  • 11
  • 56
  • 82

3 Answers3

5

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

thefourtheye
  • 233,700
  • 52
  • 457
  • 497
4

Variables in function scope are in scope throughout the entire function. It doesn't matter that the var is inside a block. So this:

function b(){
    if(false){
        var h = h * 2;
    }
    alert(h);
}

Is equivalent to this:

function b(){
    var h;
    if(false){
        h = h * 2;
    }
    alert(h);
}

It doesn't matter that the surrounding function also has a variable named h.

p.s.w.g
  • 146,324
  • 30
  • 291
  • 331
  • As you posted at the same time of thefourtheye, but you gave the hint about the fact that a.h doesn't matter in b scope in this case, I accepted yours – Rayjax Jul 18 '14 at 15:50
-1

You are re declaring 'h' using 'var.' remove the second instance of 'var.' like this:

function a(){
    var h = 1;
    function b(){
        if(false){
            h = h * 2;
        }
        alert(h);
    }
    b();
}
a();
rob.luton
  • 395
  • 1
  • 4
  • 7
  • I think you may have missed the point of the question. This code was specifically crafted to display a certain behavior and the OP would like to know why it works this way, not how to "fix" it. – James Montagne Jul 18 '14 at 15:42
  • this is not the same behavior as this will set the h of the a's scope – Rayjax Jul 18 '14 at 15:42
  • the "solution" to the problem would be to declare another variable with h's value into b's scope, and applying the * 2 on it, but as stated by @JamesMontagne, this isn't the purpose of the question – Rayjax Jul 18 '14 at 15:43
  • Right, I misunderstood. – rob.luton Jul 18 '14 at 15:45