2

I won't say anything, just a look at the code is enough:

JS:

var myvar = "my value";

(function (){
    console.log(myvar); //returning undefined
    var myvar = "local value";
})();

Now a very simple question: The variable myvar is declared before the execution of the function, so why is the console showing undefined?

codetalker
  • 576
  • 1
  • 6
  • 21
  • I'm unclear if you know Javascript does variable hoisting? [It does](http://stackoverflow.com/questions/3725546/variable-hoisting) – Liam Feb 15 '16 at 16:18
  • You can comment the `var myvar = "local value";` and check the myvar value then – swapnesh Feb 15 '16 at 16:21

2 Answers2

3

You have two variables called myvar. One inside the function and one outside the function.

Inside the function you have access to the one declared inside the function (which, as you said, is hoisted). It hasn't been assigned a value at that point, so it is undefined.

One line later, you assign it a value.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
0

Just as an addition to Quentin's post. What your code looks like "post hoist":

var myvar = "my value";

(function (){
    var myvar;
    console.log(myvar); //returning undefined
    myvar = "local value";
})();

If you look at it this way it's obvious why it's undefined.

If you want the variable to be "My value" you can do thus:

var myvar = "my value";

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

Fiddle

Liam
  • 27,717
  • 28
  • 128
  • 190