Understanding JavaScript hoisting and truthy & falsy

邮差的信 提交于 2019-11-28 12:31:46

For your example number 1, the alert is shown because you're using var inside the function and the var declaration is hoisted to the top of the function, so it is equivalent to:


var foo = 1; 
function bar() {
    var foo;
    if (!foo) {
        alert('inside if');
        foo = 10; 
    } 

} 
bar();

One might conclude that these sorts of issues offer compelling reason to declare all variables explicitly at the top of the function.

Only variable declaration is eagerly evaluated. The variable assignment in your first case (in the if block) occurs only upon entering the if block.

The variable you only declare, but not assign any value to, has the value of undefined (which coerces to false).

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