views:

5665

answers:

7

I wanted to check whether the variable is defined or not.

eg

alert( x );

Throws a not defined error
How can I catch this error?

+24  A: 

in JavaScript null is an object. There's another value for things that don't exist, undefined. The DOM returns null for almost all cases where it fails to find some structure in the document, but in JavaScript itself undefined is the value used.

Second, no, they are not directly equivalent. If you really want to check for null, do:

if (null == yourvar) // with casting
if (null === yourvar) // without casting

If you want to check if a variable exist

if (typeof yourvar != 'undefined') // Any scope
if (window['varname'] != undefined) // Global scope
if (window['varname'] != void 0) // Old browsers

If you know the variable exists but don't know if there's any value stored in it:

if (undefined != yourvar)
if (void 0 != yourvar) // for older browsers

If you want to know if a member exists independent of whether it has been assigned a value or not:

if ('membername' in object) // With inheritance
if (object.hasOwnProperty('membername')) // Without inheritance

If you want to to know whether a variable autocasts to true:

if(variablename)

I probably forgot some method as well...

Source

Natrium
undefined is not a reserved word; you (or someone else's code) can do "undefined = 3" and that will break two of your tests.
Jason S
"If you know the variable exists but don't know if there's any value stored in it" -- huh?!
Jason S
I think he is referring to a variable declared that has not been assigned to. eg:var foo; // foo exists but does not have a value
Wally Lawless
Jason S
Also from what I can tell, that section "If you know the variable exists" has no difference from the previous section. The next section ("if you want to know if a member exists independent...") is correct.
Jason S
I think you need to quantify 'old browsers'.
bobobobo
+8  A: 

technically the proper solution is (I believe)

typeof x === "undefined"

You can sometimes get lazy and use

x == null

but that allows both an undefined variable x, and a variable x containing null, to return true.

Jason S
+2  A: 

Even easier and more shorthand version would be:

if( !x ){
   //undefined
}

OR

if( typeof x != "undefined" ){
    //do something since x is defined.
}
Dmitri Farkov
the first code-piece can be incorrect if x is being set from a function call.like x = A();if A doesnt return anything, it will return "undefined" by default. Doing a !x would be true which would be logically correct. However, if A() returns 0 then !x should be false as x=0. However in JS, !0 is also true.
Rajat
A: 
try {
      if (myVar) {}
} catch (err) {
      var myVar = "";
}

Source: http://dmartin.org/weblog/javascript-checking-whether-a-variable-exists

NinethSense
Is there an advantage to doing it that way? I'd think it would be slower and it's obviously much more code than if (typeof x === "undefined").
Nosredna
More code.. yes. But No issues with performance as far as I know. Also, try-catch is a standard coding method (in any modern language).
NinethSense
This has piqued my interest. In any other language, having to throw and catch an exception is a huge overhead compared to returning a special value. What makes JavaScript special in this regard? Is it because it's so slow for every operation that you don't notice the performance degradation for exception handling?
Trejkaz
+2  A: 

I've often done:

function doSomething(variable)
{
    var undef;

    if(variable == undef)
    {
         alert('Hey moron, define this bad boy.');
    }
}
Joe
Consider changing "==" to "===". If you call doSomething(null) you will also get the alert. Unless that's what you want.
Jason S
+3  A: 

The only way to truly test if a variable is undefined is to do the following. Remember, undefined is an object in Javascript.

if (typeof var === 'undefined') {
  // Your variable is undefined
}

Some of the other solutions in this thread will lead you to believe a variable is undefined even though it has been defined (with a value of NULL or 0, for instance).

Michael Wales