Variable hoisting - “var” with global variable name in function

别等时光非礼了梦想. 提交于 2019-12-09 14:05:29

问题


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.


回答1:


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.




回答2:


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();


来源:https://stackoverflow.com/questions/21096904/variable-hoisting-var-with-global-variable-name-in-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!