Understanding JavaScript hoisting and truthy & falsy

后端 未结 2 883
一整个雨季
一整个雨季 2020-12-11 05:23

I\'ve been reading about JavaScript hoisting sometime back.

JavaScript Scoping and Hoisting by Ben Cherry
Two words about “hoisting” by Dmitry Soshnikov

相关标签:
2条回答
  • 2020-12-11 05:49

    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.

    0 讨论(0)
  • 2020-12-11 06:05

    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).

    0 讨论(0)
提交回复
热议问题