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?
Global variables can be altered by any part of the code, making it difficult to remember or reason about every possible use. A global variable can have no access control. It can not be limited to some parts of the program. Using global variables causes very tight coupling of code.
The reason global variables are bad is that they enable functions to have hidden (non-obvious, surprising, hard to detect, hard to diagnose) side effects, leading to an increase in complexity, potentially leading to Spaghetti code.
Pointers to globals are even more evil. The main problem with using global variables is that they create implicit couplings among various pieces of the program (various routines might set or modify a variable, while several more routines might read it).
Using global variables means they are visible to many classes who can manipulate the data then. So you will have to take care of your data is it is widely visible. And if you are using multithreading then you are in trouble as anybody can modify that data, so lots of scope for data getting corrupted.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With