javascript hoisting for global variable

☆樱花仙子☆ 提交于 2019-12-10 17:14:42

问题


I was wondering how javascript hoisting works for global variable.

Let's say I have following code snippet:

var a = 5;
function print(){
    console.warn("a",a,b);
    var a = 10;
    b=5;
    console.warn("a",a);
}
print();

In this case I am getting error "b is not defined". I wonder why Javascript hoisting is not working for global variable. I tried to look for this but getting results only for variable hoisting. Any thoughts??


回答1:


var statements are hoisted. function declarations are hoisted. Assignments are not hoisted (to the extent that if you combine a var statement with an assignment (var foo = 1) then the declaration part is hoisted but the assignment is not).



来源:https://stackoverflow.com/questions/26753166/javascript-hoisting-for-global-variable

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