Variable not raised

In Javascript, variables are hoisted up to the top of the scope in which they are declared.
However, in the following code, it seems that the variable is myvar

not hoisted.

<html>
<body>
</body>
</html>

<script type="text/javascript">
    console.log(typeof myvar);  

    var myvar = "value";    

    console.log(typeof myvar);  

</script>

      

Output above:

undefined
string

      

I expected the first line to say "line" because it myvar

needs to be raised above it.

Why is it wrong?

+3


source to share


2 answers


Declarations with variables, assignments are not.



By using var myvar

anywhere in a function, you create a variable with local scope myvar

, but if you follow it with = something

, then the assignment will be done in the normal code order.

+10


source


Deceiving this, and Quentin's answer is good (as always), but just to re-enact it:

The way the JavaScript engine actually handles this code is:

// 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 its value now

      



That is, this:

var myvar = "value";

      

... are actually two different things that happen twice. Variable declaration (part var myvar

) that occurs before stepping code in the scope is executed, and initialization (part myvar = "value"

; this is indeed an assignment expression at the time it is processed) that occurs when this line is in code.

+2


source







All Articles