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.
7 Answers
I got it to work using if (typeof(x) != "undefined")
6 Comments
FlySwat
you are checking if x = a string, not if x is undefined.
Paul Batum
Jonathan, are you sure about that? John Resig uses this exact approach in his javascript tutorial here: ejohn.org/apps/learn/#11 You can run the script on the page and see for yourself.
FlySwat
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.
Sophie Alpert
@Ben: The string
"undefined" is more correct – if !== is used then the quotes are necessary because typeof results in a string.Derek Prior
@BenBederson @BenAlpert, additionally,
undefined can be overridden! Use the string. |
To avoid accidental assignment, I make a habit of reversing the order of the conditional expression:
if ('undefined' !== typeof x) {
6 Comments
just mike
hey, i reverse the order too! can't remember where i learned it though...
Cipi
You want to use
!==, not ===. :)Matt Connolly
reverse assignment i hate.
Alex K
.sentences english those completely reverse
Jason Newell
This is undeniably the better way to do this, but its awkwardness bugs me (plus it's often inconsistent with other people's code). I want it to be wrong.
|
You can do that with:
if (window.x !== undefined) { // You code here }
2 Comments
Andrew Hedges
This works with "variables" in the global scope only because those are actually properties of the ''window'' object. Variables declared using the ''var'' statement will not be testable this way. More here: ahedg.es/84
Jason Newell
Also, this assumes that the global object is window, which is (usually?) the case in a browser, but isn't necessarily true in other environments.
try to use undefined
if (x !== undefined)
This is how checks for specific Browser features are done.
4 Comments
Paul Batum
Are you sure that exact syntax works Nick? It comes up as an error for me, x is undefined.
Ruan Mendes
How did this get 4 votes? It's doing almost the same wrong thing as what OP had.
Andrew Hedges
The problem with this is that undefined can be redefined, so only use this if you are certain that isn't the case in your scope.
Jason Newell
@AndrewHedges As others have pointed out, another problem is that it assumes x is declared. Try pasting "x == undefined" into a JS console and you'll get a reference error.