Why are global variables considered bad practice?

user1318416 picture user1318416 · May 10, 2012 · Viewed 33.8k times · Source

I keep seeing warnings not to use global variables in JavaScript, but it seems that the only reason people say that is because the clogs up the global namespace. I can imagine this being easily fixed by putting all of the variables into one big object. Now the question is: are there any other reasons not to use global variables other than convenience sake? Are there any performance or compatibility issues involved with them?

Answer

Elliot Bonneville picture Elliot Bonneville · May 10, 2012

They clutter up the global namespace and are slower to look up than local variables.

First of all, having many global variables is always a bad thing because it's easy to forget you declared a variable somewhere and accidentally re-declare it somewhere else. If your first variable was local then you don't have a problem. If it was global, then it just got overwritten. This gets even worse when you get into implied globals (e.g. when you say someVar = someValue without declaring someVar with the var keyword).

Secondly, global variables take longer for Javascript to "find" than local variables. The difference in speed isn't huge, but it does exist.

For further reading and a more in-depth explanation of why globals are considered bad practice, you may want to check out this page.