Ever since beginning JS a bit over a year ago, I've always had issues with variables that I declare inside of functions but want to access outside the functions. Initially, I would use a script
element above all my other scripts with every variable I wanted declared with a var x,y,z;
, or a window.x = __;
if I didn't want to add it to a list like that. That got annoying to keep up with, so when I learned about not using var
to declare things, but still being able to access them, I began to do that. Now I'm seeing things like this, which say to use var
for all variables for various reasons. Would it be possible to create an object the variables bubble up to instead of window
if there are no previous declarations of the variable, or a substitute for the var
declaration? I have the idea to do something like
window.NewVarList = [];
//or is « var NewVarList = []; » more appropriate?
function gvar(NewVar,SetVal){
window.NewVarList[NewVar] = SetVal;
//or « NewVarList[NewVar] = SetVal; »
}
but don't know how to make a variable instantly be searched for in NewVarList
(using VarInList
rather than NewVarList['VarInList']
) or how to make gvar x = __;
instantly call a gvar(x,__)
with the right types for the value I want to set to, instead of everything being a string. Would it be possible to make all variables declared without var
instantly go to the window.NewVarList
and search for them without needing a NewVarList[VarName]
? And if I can't have things instantly bubble up to NewVarList
, can I make gvar
work without needing the normal parenthesis and arguments? Or should I just go back to defining all my variables outside of my functions? Would it be safe to continue to just leave the var
declaration out of my code?