How and why to avoid global variables in JavaScript?

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= {

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


Updated on: 13-Jun-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started