why is global variable not accessible even if local variable is defined later in code [duplicate]

£可爱£侵袭症+ 提交于 2019-12-25 06:54:11

问题


why does the following code segment generate the following output?

code segment:

var a = 10;
function(){
    console.log(a);
    var a = 5;
}

output:

undefined

回答1:


Because variable is hoisted at top and in your function you have declared the variable var a = 5 which is same as following:

var a = 10;
function(){
    var a; // a = undefined
    console.log(a);//a is not defined so outputs undefined
    a = 5;
    console.log(a);//a is now 5 so outputs 5
}

And in your function scope var is being declared it doesn't see global variable but local variable i.e. var a and which is undefined.



来源:https://stackoverflow.com/questions/27199391/why-is-global-variable-not-accessible-even-if-local-variable-is-defined-later-in

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