Skip to content Skip to sidebar Skip to footer

Should Global Variables In Javascript Be Always Avoided?

I have seen, google places api docs, suggesting use of global variables outside of the functions, like: var placeSearch, pauto, geocoder; I want to use data returned from $.get,

Solution 1:

so the reason for to avoid using global variables as much as possible as stated in the previous answers. It is about easily overriding problem and troubleshooting when some global values are being overriden. From my own experience, I usually create an utility to handle sharing values. The idea is as following

//global.js
(function(){
  const context = {};
  functionsetGlobalValue(key, value) {
    context[key] = value;
  }
  functiongetGlobalValue(key) {
    return context[key];
  }
  window.setGlobalValue = setGlobalValue;
  window.getGlobalValue = getGlobalValue;
}());
// app.jsfunctioncodeAddress(address) {
  geocoder.geocode({ 'address': address}, 
  function(response, status) {
   if (status == 'OK')
    {
     var senddata = $.get('/myurl',{params}, function (data){     setGlobalValue('codeAddress', data) });
    } else {
     }
});
}
// get value hereconsole.log(getGlobalValue('codeAddress'));

by this way we can track all the global values by searching for setGlobalValue since this is the only way to set "global" value context.

Solution 2:

Avoid global variables or minimize the usage of global variables in JavaScript. This is because global variables are easily overwritten by other scripts. Global variables are not bad and not even a security concern, but it shouldn’t overwrite the values of another variable.

On the usage of more global variables in our code, it may lead to a maintenance issue. Let’s say we added a variable with the same name. In that case, get ready for some serious bugs.

To avoid the usage of global variables, use the local variables and wrap your code in closures. You can also avoid this by wrapping the variables with json:

var wrapperDemo= {
   x:5,
   y:function(myObj){
   }
};

Above, if you want to call x, then call it using:

wrapperDemo.x

Which would return 5 for you...

Solution 3:

You can just wrap everything inside self invoked function (it's closures but it's simple)

(function(){...})() means function will call itself, that's all.

Best practice is when you wrap every .js file inside this self invoked function so it's not global.

Your code:

(function(){
var glo_var;

functioncallback(data){
         glo_var = data;
}

functioncodeAddress(address) {
    geocoder.geocode({ 'address': address}, 
    function(response, status) {
     if (status == 'OK')
      {
       var senddata = $.get('/myurl',{params}, function (data){ callback(data) });
      } else {
       }
  });
}
})();

Post a Comment for "Should Global Variables In Javascript Be Always Avoided?"