Global object undefined check method

Hi all,

I’m trying to create a global object to contain all my variables. I want to place a check to see whether my global variable name is taken. Like so:


if( typeof globalVar == "undefined"){
   globalVar = {};
}
else{
    // Check if 'globalVar1' is defined and then keep iterating.
}

If ‘globalVar’ is defined, check whether ‘globalVar1’ is defined. So, as you can see there are two questions from me.

  1. How do I check at runtime whether the variable ‘globalVar1’ exist?
  2. Even if the variable ‘globalVar1’ exist, how would I update the rest of my code to use the newly created ‘globalVar1’ global obj?

Please help

It’s times like these that an array becomes of incredibly good use.


if (!globalVar) {
globalVar = [];
}
globalVar.push({...});

That will add an object to the globalVar array regardless of whether globalVar exists or not.

Thanks for the help. What about a situation where an application has multiple js plugins and you’re creating a plugin of your own? In this case, I want to check if up until this point any library has created a global variable (object, array, etc) with, let’s say, ‘globalVar’.

Is there any particular reason why your global object needs a name? If you are not going to reference it from anywhere else then you could use an anonymous global object which therefore wouldn’t clash with any other object because it doesn’t have a name to clash with.

Thanks