JavaScript hoisting explanation

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

    return function a(){};
    

    Here function ... is an expression. A named function expression to be precise. The a here doesn't matter much, it just gives the anonymous function a .name, but it's still just a function expression that you're returning.

    return 
    function a(){};
    

    This here is equivalent to:

    return;
    function a(){};
    

    Here function a is a declaration, not an expression. It is hoisted, creating a local name a in the scope, shadowing the outer a. I.e. it is equivalent to:

    function b(){
        var a = function () {};
        a = 10;
        return;
    }
    

提交回复
热议问题