JavaScript hoisting explanation

前端 未结 4 2310
一整个雨季
一整个雨季 2020-12-14 14:01

What is the difference between below snippets?

var a = 0;
function b(){
    a = 10;
    return function a(){};
}
b();
console.log(a);  // => 10

4条回答
  •  渐次进展
    2020-12-14 14:47

    Let's assume.

    You are playing cricket. bowler is on the way and you just hit your bat on the air.

    Would it be shot? No!

    So if we assume Hoisting is cricket, therefore there is no sense to hit ball till bowler does not throw the ball

    Quick Example:

    Hoisted

    console.log('batsman hit but ', ballStatus()); // batsman hit but  true
    
    
    function ballStatus() {
        return true;
    }
    
    

    Non-Hoisted

     console.log('batsman hit but ', ballStatus()); // Uncaught TypeError: ballStatus is not a function
    
     var ballStatus = function() {
        return true;
     }
    
    

提交回复
热议问题