How hoisting name resolution order works in JavaScript?

给你一囗甜甜゛ 提交于 2019-12-06 10:08:22

Lets leave the function foo for the moment. Within a function, if a variable is declared anywhere inside that function, the declaration will be moved to the top of the function. So, it is actually evaluated like this

function bar() {
    var foo;
    return foo;
    foo = 10;
    foo = '11';
}

But when you have a function declared by the same name, it will take precedence and it will be evaluated similar to this

function bar() {
    var foo = function() {};
    return foo;
    foo = 10;
    foo = '11';
}

That is why you are getting function in the alert box.

Any variable without var inside a function becomes a global variable by default.

when you have a function declaration inside another function(like in your example), it gets hoisted first followed by the variable declarations.

examples to demonstrate variable overriding.

function bar() {
    var foo = 10;
    function foo() {}
    return foo;
}

bar(); //--> returns 10;

function bar() {
   var foo;
   function foo() {}
   return foo;
}

bar(); //--> returns the function object foo.
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!