Can you clarify this JavaScript variable hoisting behavior?

前端 未结 3 1631
-上瘾入骨i
-上瘾入骨i 2021-01-25 14:22

Case1:

var text = \'outside\';
function logIt(){
    console.log(text);
    text =\'inside\';
}
logIt(); //prints outside. why?

I thought the

3条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-25 14:54

    It's the variable declaration that's getting hoisted, not the assignment.

    In the first function you're only overriding the value of text after the call to console.log, but no other text is being introduced to the local scope of the function.

    In the second case, you are introducing a new text variable that is local (and initialized to undefined, as expected), and due to variable hoisting, the actual var text line is interpreted before the call to console.log, hence the undefined.

    See MDN

提交回复
热议问题