This question already has answers here:
Closed 9 years ago.
Possible Duplicate:
Why is it bad to make elements global variables in Javascript?
In the JavaScript bible, it is said that global variables (variables declared without the "var" keyword) are a very bad thing. Ok, comparing to strongly typed languages like Java or C++ JavaScript is like a street gang slang (was!).
But are there any performance problems? Or is it causing the browser to crash? Or are there some actual noticeable difference when using globals?
I have learned JavaScript on my own and I follow the guidelines of the books and experts, but it will be nice to know why this is such an important subject.
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.
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.
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.