Monday, June 3, 2024
153
rated 0 times [  159] [ 6]  / answers: 1 / hits: 43892  / 12 Years ago, wed, may 9, 2012, 12:00:00

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?


More From » global-variables

 Answers
4

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.


[#85682] Tuesday, May 8, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
gideons

Total Points: 197
Total Questions: 106
Total Answers: 108

Location: Moldova
Member since Sat, Jan 29, 2022
2 Years ago
gideons questions
Tue, Nov 9, 21, 00:00, 3 Years ago
Sat, Jan 2, 21, 00:00, 3 Years ago
Wed, Oct 28, 20, 00:00, 4 Years ago
Thu, May 21, 20, 00:00, 4 Years ago
;