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.

Solution:

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 
    })();

Continue reading