Variable not hoisted

后端 未结 2 371
死守一世寂寞
死守一世寂寞 2021-01-21 01:33

In Javascript variables are hoisted to the top of the scope they are declared within.
However in the following code it seems that the variable myvar is not hois

相关标签:
2条回答
  • 2021-01-21 01:46

    Variable declarations are hoisted, the assignments are not.

    By using var myvar anywhere in the function you create a locally scoped variable myvar, but if you follow it with = something then the assignment will take place in normal code order.

    0 讨论(0)
  • 2021-01-21 01:47

    A dupe of this came up, and Quentin's answer is good (as always), but just to spell it out even more:

    The way the JavaScript engine actually processes that code is like this:

    // Before any step-by-step code
    var myvar;
    // Now step-by-step starts
    console.log(typeof myvar);  // undefined since no value has been written to it
    myvar = "value";    
    console.log(typeof myvar);  // "value" because that's its value now
    

    That is, this:

    var myvar = "value";
    

    ... is actually two separate things that happen at two separate times. The variable declaration (the var myvar part), which happens before any step-by-step code in the scope is run, and the initialization (the myvar = "value" part; it's really an assignment expression by the time it's processed), which happens where that line is in the code.

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