Why global variables are evil in JavaScript

First what are global variables ?

Global variables are variables that are accessible from every scope in your JavaScript, even in different files referenced in the same page.

When i started to learn JavaScript, i thought that using global variables is a great thing. But that was totally wrong, because it’s easy to overwrite the values of it unintentionally as they are accessible from anywhere in your code, and if you didn’t notice that two variables have been overwritten. you might be in a big trouble, your code will be throwing errors, and it will be hard to figure out the reason of these errors.


the solution is to encapsulate your code, And because JavaScript has ‘function level scope‘ so you could just write all your code within a self-executing, anonymous function:

   (function () {
        var x = 10, 
            y = 20;
        // code goes here 

Note: These two little brackets at the end of the function, cause everything contained within the parentheses to be executed immediately.

Now no code outside the scope of this anonymous function can access any of the variables or functions defined within it.

If you want to allow access to a variable or function outside its scope, just expose it to the global ‘window’ object.

 (function () {
        var x = 10,
            y = 20;

        function sum(){
              return x + y;

        window.sum = sum;


the benefit of this pattern it that now you can limit access to variables or functions within your closure, by making them private and only choose what to expose to your global scope.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s