Join the Stack Overflow Community
Stack Overflow is a community of 4.7 million programmers, just like you, helping each other.
Join them; it only takes a minute:
Sign up

i am not asking if the variable is undefined or if it is null.i want to check if the variable exist or not. is this possible?

share|improve this question
8  
It's just my opinion, but it seems to be a bad approach any logic based on checking if a variable or function exists. If your logic expects some variable, I honestly believe that this is a semantic or syntax error rather than a logical decision. – Matías Fidemraizer May 4 '11 at 6:21
up vote 13 down vote accepted

The typeof techniques don't work because they don't distinguish between when a variable has not been declared at all and when a variable has been declared but not assigned a value, or declared and set equal to undefined.

But if you try to use a variable that hasn't been declared in an if condition (or on the right-hand side of an assignment) you get an error. So this should work:

var exists = true;
try {
    if (someVar)
        exists = true;
} catch(e) { exists = false; }
if (exists)
   // do something - exists only == true if someVar has been declared somewhere.
share|improve this answer
1  
+1 For the explanation and solution. Consider this modification: var exists = false; try { eval("someVar"); exists = true } catch (e) { }; if (exists) ... -- the eval() is to prevent a super-smart Javascript engine from optimizing it away. It will also trick most other static analysis. – user166390 May 4 '11 at 6:43
    
Yeah, even ignoring potential optimisation I realised after posting that having an extra exists = true; inside the try block was both redundant and confusing given it isn't really part of the logic: if (someVar) {} should've done the trick given the point of the if() is just to try to crash and not to do something if it works. An assignment might have been a better choice than an if, or, as you say, an eval. – nnnnnn May 4 '11 at 7:20
    
It can be as simple as var exists = true; try {someVar} catch(e) {exists = false;}. – RobG Nov 10 '15 at 2:16
if ('bob' in window) console.log(bob);

Keep in mind with this way, even if you declared a variable with var, that would mean it exists.

share|improve this answer
2  
This isn't correct. window.bob = false is a counter-example. – user166390 May 4 '11 at 6:23
    
Ok scratched that and wrote a new one. – Mauvis Ledford May 4 '11 at 6:52
    
This only works for global variables. – nnnnnn Sep 15 at 21:07

I use this function:

function exists(varname){
    try {
        var x = eval(varname);
        return true;
    } catch(e) { return false; }
}

Hope this helps.

share|improve this answer
    
What if the variable isn't global? (Or do you declare that function inside whatever function needs it?) – nnnnnn Sep 15 at 21:03

When you try to access a variable which is not declared in the context, you will see that the error message says it is undefined. This is the real check you may perform to see if the variable if defined or not than null check.

share|improve this answer

If you don't need to know at runtime use JSLint. Also remember that javascript var statements are hoisted, so even if the var is inside an if block it will still be defined.

Honestly I think if you are not sure if a variable is defined you are doing something wrong and should refactor your code.

share|improve this answer

try this

var ex=false;
try {(ex=myvar)||(ex=true)}catch(e) {}
alert(ex);

where ex is true if myvar has been declared.

working example: http://jsfiddle.net/wcqLz/

share|improve this answer

I think it depends on what you want to do with the variable.

Let's say, for example, you have a JS library that will call a function if it has been defined and if not, then not. You probably know already that functions are first level objects in JS and are as such variables.

You could be tempted to ask first if it exists, and then call it. But you can just as well wrap the attempt at calling it in a try/catch block.

Example of code that calls a function, if defined, before and after firing an event:

function fireEvent(event)
{
    try
    {
        willFireEvent(event); // Is maybe NOT defined!
    } catch(e) {}

    //... perform handler lookup and event handling

    try
    {
        hasFiredEvent(event); // Might also NOT exist!
    } catch(e) {}
}

So instead of checking for the variable, catch the error instead:

var x;

try
{
    x = mayBeUndefinedVar;
}
catch (e)
{
    x = 0;
}

Whether this is a good thing or not in terms of performance, etc., depends on what you're doing...

share|improve this answer

What you're after is:

window.hasOwnProperty("varname");

A safer approach might even be:

this.hasOwnProperty("varname");

Depends on your calling context though...

share|improve this answer
    
What if the variable isn't global? Then it won't be a property of window or this. – nnnnnn Sep 15 at 21:06

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.