Skip to content Skip to sidebar Skip to footer

Javascript Variable Scope Return "undefined"

There is one sentence in JavaScript Guide about variable scope:'Variables in JavaScript are in a sense 'hoisted' or lifted to the top of the function or statement. However, variabl

Solution 1:

Because all variable declarations are automatically hoisted to the top of their defining function block, this code:

(function() {
  console.log(myvar); // undefinedvar myvar = "local value";
})();

is actually this to the JS interpreter:

(function() {
  var myvar;   // declares a new local variable that covers up the global nameconsole.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";
})();

Solution 2:

Here your function is a self invoking function. A self-invoking expression is invoked (started) automatically, without being called. Hoisting applies to variable declarations and to function declarations.

var myvar = "my value";

(function() {
  console.log(myvar); // undefinedvar myvar = "local value";
})();

So here function invoked it self even before initializing myvar with the specified value

Post a Comment for "Javascript Variable Scope Return "undefined""