Variable not hoisted

后端 未结 2 370
死守一世寂寞
死守一世寂寞 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: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.

提交回复
热议问题