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?
source to share
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.
source to share