JavaScript hoisting explanation

前端 未结 4 2287
一整个雨季
一整个雨季 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:40

    return
    function a() {}
    

    is same as

    return;
    function a() {}
    

    after automatic semicolon insertion. In second case, function a is moved to the top of its scope. The code is same as

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

    As a inside b() is inner function and then overriden, it is not accessible from outside of b().

    Here is the demo to understand how the hoisting works.

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

提交回复
热议问题