Understanding JavaScript hoisting and truthy & falsy

后端 未结 2 888
一整个雨季
一整个雨季 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.

提交回复
热议问题