Can you clarify this JavaScript variable hoisting behavior?

前端 未结 3 1630
-上瘾入骨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

    0 讨论(0)
  • 2021-01-25 14:58

    Hoisting: You can understand it as Entire function body is taken at the top of the script along with variables which have a value of undefined (if using them before assignment is done)

    Now Case1:

    At the time when you are calling the function and the console.log executes the value of text is still "outside"

    And after console log it changes value to "inside"

    If you write console.log immediately after calling logIt(), it will display "inside" then.

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

    Case 2: In this case you are making a new var inside the function logIt which will then be hoisted as var text = undefined (as you are using it before assignment)

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

    Try printing console.log(text) after calling function this time. It will print "outside in this case as global scope has no effect because of logIt function in this case"

    0 讨论(0)
  • 2021-01-25 15:08

    Because of hoisting the inner variable text is moved to the beginning of the function. But only it's name portion:

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

    Case 1 logs "outside", because text is a variable in the surrounding scope of logIt and hence accessible within logIt. You reassign text lexically after the console.log call. So this reassingment isn't considered.

    0 讨论(0)
提交回复
热议问题