Search code examples
javascripthoisting

Can you clarify this JavaScript variable hoisting behavior?


Case1:

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

I thought the text inside the function logIt() will be hoisted to the top of the function and will print undefined?

Case2:

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

This one prints undefined as expected. Could someone explain why in case1 we getting the value outside?


Solution

  • 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