How and why to avoid global variables in JavaScript?

JavascriptWeb DevelopmentFront End Technology

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 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.
raja
Ali
Published on 22-Jan-2018 15:36:54
Advertisements