4

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?

2
  • typeof window["string"] === "object" Commented May 28, 2012 at 16:25
  • 1
    I would add a && window["string"] !== null to that to circumvent the typeof null being object Commented May 28, 2012 at 16:26

5 Answers 5

7

If the object is in the global scope;

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

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

1
if( window[input])...

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

4 Comments

Will give incorrect result for variables that are defined but have falsy values.
@Amadan Since we're testing for objects, and no object (not even an empty one) has a falsy value, this is perfectly acceptable.
Oh, missed the part about it having to be an object.
No problem, it's fair enough. Strictly speaking it should be checking its type against undefined, but this is a case of circumstances altering requirements.
1

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
}

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.