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
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.
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.