What Is So Bad About Global Variables?
Solution 1:
Global variables can have unintended side effects (action at a distance).
For example, when you intent to use a local variable i
and forget the var
and some other code (that ran before) did the same, then you start your usage with that variables old value. That can throw your code wildly of its track and can be hard to track down ("How did that value end up here?").
Just a few days ago there was a question about a similar problem (in Java, however) and it led to much confusion.
Apart from that it increases the scope of your variable which means that its memory can't be reclaimed even if you no longer need access to it, which will lead to memory leaks.
Solution 2:
If one takes a good structured approach, global variables are perfectly acceptable to use, and actually save a bit of overhead with all the passing around / copying of various pointers / variables.
For me, using local vars is more a matter of how easy it makes the code to maintain, debug, and port to other systems.
Solution 3:
I would say there are two main issues here:
- Hoisting
- Redefinition of external variables
The hoisting issue comes out mainly when trying to define the same variable inside what you might believe are different scopes, but really aren't (say, inside and outside the braces of an if statement).
JavaScript pushes all variables definitions up and then assigns the value wherever the variable was declared and assigned originally. This might end up in some weird bugs where you, without noticing, might be redefining your own global variables (scary...)
The other issue is that, if you're using external libraries in your project, you can easily override an already defined variable and, as a consequence, lose some of the functionality offered (which you probably don't wanna do) and introduce subtle bugs (again).
I would recommend to embrace local variables as much as possible, or you can use "namespaces" to separate them.
The worst is that for both issues JavaScript will remain silent, so they become hard to find bugs.
Post a Comment for "What Is So Bad About Global Variables?"