Why are global variables considered bad practice? Why are global variables considered bad practice? javascript javascript

Why are global variables considered bad practice?


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.


Global variables can significantly increase coupling, significantly reduces the scalability and testability of your code. Once you start using globals, you now have to know where and how the variable is modified (i.e. breaking encapsulation). Most of the literature and conventions out there will argue that performance is the least of your concerns when using globals.

This is a fantastic article outlining why global variables cause headaches.


In a nutshell, Global variables cause (and more) the following issues.

1) Variable naming collisions - If you're working on a team and both yourself and your co-worker use the same variable name on the global scope, the variable defined last will overwrite the initial variable. This obvious can have devastating consequences.

2) Security - Specifically on the web, every user has access to the Window (or global) object. By putting variables on the global scope, you give any user the ability to see or change your variables.

3) Slower - This is arguably negligible, but it still exists. The way JavaScript variable lookups work is the JavaScript engine will do a lookup on the current scope the variable is being looked up in. If it can't find it, it will do a look up on the next parent scope. If it doesn't find it there, it will continue looking upward until it reaches the global object looking for that variable. If all of your variables are located on the global scope, the JavaScript engine will always have to go through every scope in order to finally reach the global scope to find the variable.