Avoid Global Variables (JavaScript Tips)



Global variables are a terribly bad idea.

Lets see how to avoid global variable in JavaScript :

For example lets consider below code :

var current = 0;  // current is a global variable 

function show(){
   current = 1;
   alert(current);
}


Best Practice :

var module = function(){
        var current  = 0;
        var show = function (){
                  current = 1;
                  alert(current); 
        };
        return {show:show, current:current};
}();

show() function calling process : module.show();

Collected From :  
https://www.thinkful.com/learn/javascript-best-practices-1/Make-it-Understandable#Avoid-Globals

 

Leave a Reply