Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In JSFiddle, why is this global variable not defined on `window`?

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.)

like image 442
Sushant Prasad Avatar asked Dec 31 '25 20:12

Sushant Prasad


1 Answers

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.

like image 200
apsillers Avatar answered Jan 02 '26 09:01

apsillers