Because all variable declarations are automatically hoisted to the top of their defining function block, this code:
(function() {
console.log(myvar); // undefined
var myvar = "local value";
})();
is actually this to the JS interpreter:
(function() {
var myvar; // declares a new local variable that covers up the global name
console.log(myvar); // undefined
myvar = "local value";
})();
Which should show you why the locally defined myvar
is what console.log()
outputs and it has been defined, but not yet initialized so thus it shows as undefined
.
The locally defined myvar
overrides/covers up the globally defined one so when you access myvar
in your function, you only get the locally defined variable (whether it's been initialized yet or not).
See some other references on the same topic:
How do JavaScript variables work?
JavaScript variable undefined vs not defined
One var per function in JavaScript?
JavaScript 'hoisting'
If you remove the var
in your function (so you are just referencing a variable, not declaring a new one), then you would only have one global variable named myvar
and you would get the behavior it looks like you may be expecting:
var myvar = "my value";
(function() {
console.log(myvar); // outputs "my value"
myvar = "local value";
})();