Javascript and the global window
« Thursday, April 11, 2013 »

javascript

Global scope pollution isn't a language problem in itself. Since javascript doesn't have any concept of package/module yet. Any variable created without using the keyword var will get binded to the global scope or to the closest closure that defines it to the of the function keyword.

1
2
function FeedMeCookies() {
}

Is an equivalent to the use of var with anonym functions.

var FeedMeCookies = function() {
}

For that reason, functions are function scoped just like variables created with var. One other big point about the var keyword is that variables created with var are scoped to the current function. It's not important where the var is declared within a function.

Here is a small example.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
function A() {
    var a = 0;

    function B() {
        a = 5;

        var a = 3;
        return a;
    }

    console.log(B());

    return a;
}

When we call the function A, that contains a function B and a variable a. Within the function B, we update the variable a and then create with var the variable a with the value 5. The question here is, what will return the function A.

I see two possible solutions, either 5 or 0. One could think that updating a in B before the keyword var would update the variable in the clojure above. The truth is that when B is being created, javascript will check for var keyword and create every symbols it finds at the function scope. For that reasons, the answer is 0. It creates a variable a in B and any changes to a are limited to the function level. Since the a in A is never reached by B. It will return 0. Also, function B will return 3 as expected.

In more recent version of javascript, there is the new keyword let that will create variables at a scope level. In the future, this keyword should be used instead of var.

Conclusion

Global scope pollution can be easily avoided by declaring all variables or using the “strict mode”;. It's not a big problem in itself but when writing javascript, it is quite important to understand how variable declaration works to prevent pollution. Avoiding pollution of the global scope will prevent conflicts with other libraries and unpredictable behaviors.

comments powered by Disqus

Copyright © 2015 Loïc Faure-Lacroix