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.
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.
To avoid accidental assignment, I make a habit of reversing the order of the conditional expression:
if ('undefined' !== typeof x) {
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();
}
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();