user1801879
user1801879

Reputation: 822

Why is javascript treating in function (local) variables as global (window) variables?

I've a javascript file which has in function (local) variables. For example in the code below there are variables: countries, arr, india, usa, uae, australia, canada, kuwait etc. When I launch my website all of these variables are accessible with window.xyz (e.g. window.countries, window.usa etc...). I'm really confused why this would happen. I would really appreciate if someone can help me understand this.

MyApp.Helpers.LocationEducationHelper = function() {

function getPopularCountriesArray(){
    // var me = this;
    arr = [];
    countries = MyApp.getAllCountries();
    india = countries.get("IN");
    usa = countries.get("US");
    uae = countries.get("AE");
    australia = countries.get("AU");
    canada = countries.get("CA");
    kuwait = countries.get("KW");
    nz = countries.get("NZ");
    pk = countries.get("PK");
    russia = countries.get("RU");
    saudiArabia = countries.get("SA");
    southAfrica = countries.get("ZA")
    gb = countries.get("GB");
    arr.push(india, usa, gb, uae, canada, australia, nz, pk, kuwait, russia, saudiArabia, southAfrica);
    return arr
};
return {
    getPopularCountriesArray : getPopularCountriesArray
};};

Upvotes: 1

Views: 45

Answers (3)

Ninja
Ninja

Reputation: 2098

Variable declared locally inside a function, without "var" treated as global variable. If you want to limit the scope use "var".

Global Declaration

var x = 4; //global variable
(function(){
    console.log(x); //returns 4
})();
console.log(x); //returns 4

Local declaration

(function(){
    var y = 4; //local variable
    console.log(y); //returns 4
})();
console.log(y); // Reference error y is not defined

Local without var

(function(){
    z = 4; //global variable
    console.log(z); //returns 4
})();
console.log(z); // returns 4

Upvotes: 1

colecmc
colecmc

Reputation: 3318

You could rewrite it like this.

MyApp.Helpers.LocationEducationHelper = function() {

function getPopularCountriesArray(){
    // var me = this;
    var arr = [],
    countries = MyApp.getAllCountries(),
    india = countries.get("IN"),
    usa = countries.get("US"),
    uae = countries.get("AE"),
    australia = countries.get("AU"),
    canada = countries.get("CA"),
    kuwait = countries.get("KW"),
    nz = countries.get("NZ"),
    pk = countries.get("PK"),
    russia = countries.get("RU"),
    saudiArabia = countries.get("SA"),
    southAfrica = countries.get("ZA"),
    gb = countries.get("GB");

    arr.push(india, usa, gb, uae, canada, australia, nz, pk, kuwait, russia, saudiArabia, southAfrica);
    return arr
};
return {
    getPopularCountriesArray : getPopularCountriesArray
};};

Upvotes: 0

Payson
Payson

Reputation: 538

add var before each variable. it's treated as global without it

Upvotes: 3

Related Questions