I've heard that global variables in JavaScript are bad, and I can understand some of the namespace issues, etc. But why shouldn't I use a global variable for something that never gets changed throughout the script--like the date? (Which changes day to day, of course, but only ever gets referenced and not changed throughout the script.)
You can use globals if they are protected in what you think is a unique namespace and are only used when beneficial. The main issue is that globals can make one piece of code more likely to conflict with some other piece of code (if not using different namespaces or very unique names). For this reason and others, it is best to avoid globals when they are not actually needed (when variables declared local to some scope would work just as well), but there are still some appropriate reasons to have globals. The main point of education is that many people use globals when they are simply not needed. If you need them or find they are more efficient, then you can use them just fine as long as you protect the namespace from accidental collision.
I personally create one top level, global object and hang all my other globals off that one object.
Some other issues with globals:
for (i = 0; i < m.length; i++)
construct before. It can be tough to track down what is wrong.window
object so they can conflict not only with other globals, but also anything else on the window object.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