Pergunta

I was practicing some scenario and find a case:

Here is fiddle

According to closure bar function should have access to var x so I expected to alert 1 and condition get false due to if(!1) but it alerted undefined and condition get true and second alert is with value 10.

var x = 1;
function bar() {
    alert(x);
    if (!x) {
        var x = 10;
    }
    alert(x);
}
bar();

So I am confused why it is prompting undefined?

According to hoisting in a particular scope you define a variable anywhere it is considered as defined at top always.

If it is due to hoisting effect it still have to alert 10 instead of undefined.

Foi útil?

Solução

Hoisting causes a variable to be declared everywhere in the function, not defined.

On the first line of bar, since there is var x on line 3 of the function, the global x is masked and you see the local x (which is undefined since it hasn't been given a value yet).

On line 3 of bar, you have x = 10 which defines the variable. This is not hoisted.

On line 5, you alert it, and it is now defined.

Venn Diagram of the above

Outras dicas

Hoisting will make your code effectively work like this:

var x;
x = 1;
function bar() {
    var x; //same as var x = undefined;
    alert(x);
    if (!x) {
        x = 10;
    }
    alert(x);
}
bar();
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top