I’m new to javascript, from what I’m reading global variables are bad practice since they pollute the global namespace. One of the
issues I’m constantly running into is variable scope. I read somewhere that one way to solve both issues is to create an empty object:
allvars = {}
And then to stick any variables I would otherwise set as global, as properties inside this object:
allvars.animal = 'bear';
allvars.sliderSpeed = 1000;
So far this seems like a great idea to me, since now I can access my variables anywhere no matter the scope and also since all vars are inside this
object they are not global.
So is there a downside to this way of doing things? Is there a better way?
If these variables truly need to be global in scope and accessible everywhere, then this is the preferred way of doing so because it only introduces one global variable
allvarsinto the global namespace. If I were you, I’d make that one global name a bit more unique so it’s less likely to conflict with anything else. But, other than that, you’re on the right track.When one really gets into object oriented programming, there tend to be fewer and fewer things that truly need to be global as you can store most of your state on relevant (non-global) objects and access them there. Obviously, we don’t know your application in this case so we can’t really comment on whether these settings need to be global or not.