0

I have code in which i have two variable with same name. first variable is global and other one is inside the function. as per specification all global variables are attached to the window object but when i was trying to access global variable inside function it is showing undefined in jsfiddle but same code is working fine in console.

  var myVar='10';
  function check() {
    alert('Local : ' + myVar+ ', Global : ' + window.myVar); //window.myVar is undefined in jsfiddle
    var myVar;
  }

 check(); 

What is the reason of this unexpected behavior?

Here is JSFiddle

Akhlesh
  • 2,389
  • 1
  • 16
  • 23
  • 1
    check here: http://stackoverflow.com/questions/18835396/global-vars-with-jsfiddle – Dave Briand Jun 30 '14 at 11:25
  • 1
    duplicate of http://stackoverflow.com/questions/4862193/javascript-global-variables – Ashish Kasma Jun 30 '14 at 11:26
  • Access global variable as normal way don't use window.myVar it should be myVar. As well as you have defined myvar as a local variable it is undefined so you will get undefined inside the local context – Nishan Senevirathna Jun 30 '14 at 11:27
  • @NishanSenevirathna if i have variable with same name inside a function then i have to use window to access global variable. – Akhlesh Jun 30 '14 at 11:30

1 Answers1

1

for this you should know how fiddle works, Here in your case you have selected the onLoad option, so your code excutes when the whole page is loaded like a document.ready function,so it isn't an independent script. Check this

var myVar='10';
alert(window.myVar);
function check() {

    var myVar= 5;    
    // Your are defining a local variable in this function
    // so, the global one is not visible.
    alert('Local : ' + myVar+ ', Global : ' + window.myVar);
}

check(); 

http://jsfiddle.net/sJ8Eu/1/

what i changed is , i selected the option to wrap the code in the head, so it acts like a script tag. And it works fine

Amarnath R Shenoy
  • 5,121
  • 8
  • 24
  • 32