Can you clarify this JavaScript variable hoisting behavior?

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

提交回复
热议问题