tags:

views:

2739

answers:

9

How can i check in JavaScript if a variable is defined in a page? Suppose I want to check if a variable named "x" is defined in a page, if I do if(x != null), it gives me an error.

+4  A: 

try to use undefined

if (x !== undefined)

This is how checks for specific Browser features are done.

Nick Berardi
Are you sure that exact syntax works Nick? It comes up as an error for me, x is undefined.
Paul Batum
A: 
if (foo !== undefined)
David Dorward
will throw a ReferenceError if `foo` is not declared.
no
+10  A: 

I got it to work using "if (typeof(x) != "undefined")" thank you.

SSharma
you are checking if x = a string, not if x is undefined.
FlySwat
Jonathan, are you sure about that? John Resig uses this exact approach in his javascript tutorial here: http://ejohn.org/apps/learn/#11You can run the script on the page and see for yourself.
Paul Batum
I just checked it in firebug, and undefined does map to the string "undefined", someone was seriously smoking crack when they wrote JS, I stand corrected.
FlySwat
+7  A: 

The typeof operator, unlike the other operators, doens't throws a ReferenceError exception when used with an undeclared symbol, so its safe to use...

if (typeof a != "undefined") {
    a();
}
Pablo Cabrera
A: 

Assuming your function or variable is defined in the typical "global" (see: window's) scope, I much prefer:

if (window.a != null) {
   a();
}

or even the following, if you're checking for a function's existence:

if (window.a) a();
kamens
+2  A: 

To avoid accidental assignment, I make a habit of reversing the order of the conditional expression:

if ('undefined' !== typeof x) {
Andrew Hedges
hey, i reverse the order too! can't remember where i learned it though...
just mike
You want to use `!==`, not `===`. :)
Cipi
Details, details! ;-)
Andrew Hedges
A: 

All of these ways leave unpleasant "Error" messages in my JavaScript console (in my FireFox Web Developer Toolbar). Any idea how to avoid this?

Basically if you try, in any way, shape, or form to access a variable that doesn't exist, you'll get a reference error. Now, if you compare the *type* of a variable to "undefined", you're cool and groovy.So, long story short: if (typof variable == 'undefined) { // it don't exist yet } else { // variable exists, cause for celebration }
Paul Sweeney
A: 

You can do that with:

if (window.x !== undefined) { // You code here }

Sébastien Grosjean - ZenCocoon
A: 

As others have mentioned, the typeof operator can evaluate even an undeclared identifier without throwing an error.

alert (typeof sdgfsdgsd);

Will show "undefined," where something like

alert (sdgfsdgsd);

will throw a ReferenceError.

no