3

I have this code in a fiddle:

var a = 1;  

function b() {  
    var a = 10;  
    alert(window.a);  
}  

b();  

Why is a is undefined here? It's already defined in global namespace, i.e., window. (See the fiddle for an example of this unexpected behavior.)

apsillers
  • 112,806
  • 17
  • 235
  • 239
Sushant Prasad
  • 122
  • 1
  • 10
  • I mean if i write 1st statement without var then a = 1 but with var a = undefined. – Sushant Prasad Oct 12 '15 at 11:46
  • 3
    I tried it and it alerted `1`. – Samuli Hakoniemi Oct 12 '15 at 11:47
  • works for me as well – Java_User Oct 12 '15 at 11:47
  • 3
    Is this whole code running inside another scope? Perhaps a jsfiddle with its default (wrap in onload) settings? For example: [default settings](http://jsfiddle.net/syvbnqdw/), and [changed to nowrap, place in head](http://jsfiddle.net/syvbnqdw/1/) (this one works as expected). – James Thorpe Oct 12 '15 at 11:50
  • 1
    Its works for me on chrome and ie11 with an alert of `1`. Did you use another browser? Was the code encapsulate in other bracket? – SerCrAsH Oct 12 '15 at 11:55
  • If you remove the window and just call it alert(a); it works on all the browsers. There is a problem that you assign the global variable inside inner scope and try to call the global variable in a scope that has 2 - "a" parameters ;] – dlght Oct 12 '15 at 12:01

1 Answers1

4

If you're running this code in a fiddle that does not have the location set to "No wrap", or any circumstance in which you're not at the top-level scope, your outer a is not the global variable window.a. Consider a simple example where your code is wrapped inside a function called wrappingFunc:

// THIS would be the global `a`, outside `wrappingFunc`
var a = "now the global a is defined";

function wrappingFunc() {
    // this is NOT the global `a`
    var a = 1;  

    function b() {  
        var a = 10;  
        alert(window.a);  
    }  

    b();  
}

wrappingFunc();

This is exactly what JSFiddle does when you set the location to onLoad or onDomready. (See What is the difference between onLoad, onDomready, No wrap - in <head>, and No wrap - in <body>?) My wrappingFunc example is in actuality an onload or ondomready listener function, which prevents the keep from running in a global context.

Community
  • 1
  • 1
apsillers
  • 112,806
  • 17
  • 235
  • 239