Naigel
Naigel

Reputation: 9644

check if JS object exists

I need to discover at runtime if an object with a given name exists, but this name is stored in a variable as a string.

For example, in my Javascript I have an object named test, then at runtime I write the word "text" in a box, and I store this string in a variable, let's name it input. How can I check if a variable named with the string stored in input variable exist?

Upvotes: 4

Views: 13976

Answers (5)

quevedo
quevedo

Reputation: 151

I'm writing my code but not allways can know if a method exists. I load my js files depending on requests. Also I have methods to bind objects "via" ajax responses and need to know, if they must call the default callbacks or werther or not particular a method is available. So a test like :

function doesItExist(oName){ 
   var e = (typeof window[oName] !== "undefined"); 
   return e;
}

is suitable for me.

Upvotes: 0

Alex K.
Alex K.

Reputation: 175768

If the object is in the global scope;

var exists = (typeof window["test"] !== "undefined");

Upvotes: 7

Zach
Zach

Reputation: 7930

If you want to see whether it exists as a global variable, you can check for a member variable on the window object. window is the global object, so its members are globals.

if (typeof window['my_objname_str'] != 'undefined')
{
    // my_objname_str is defined
}

Upvotes: 1

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324620

if( window[input])...

All global variables are properties of the window object. [] notation allows you to get them by an expression.

Upvotes: 1

Amadan
Amadan

Reputation: 198324

If you're in a browser (i.e. not Node):

var varName = 'myVar';
if (typeof(window[varName]) == 'undefined') {
  console.log("Variable " + varName + " not defined");
} else {
  console.log("Variable " + varName + " defined");
}

However, let me say that I would find it very hard to justify writing this code in a project. You should know what variables you have, unless you expect people to write plugins to your code or something.

Upvotes: 1

Related Questions