How Can I Determine If A Javascript Variable Is Defined In A Page?
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.
Solution 1:
I got it to work using if (typeof(x) != "undefined")
Solution 2:
To avoid accidental assignment, I make a habit of reversing the order of the conditional expression:
if ('undefined' !== typeof x) {
Solution 3:
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();
}
Solution 4:
You can do that with:
if (window.x !== undefined) { // You code here }
Solution 5:
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.
Post a Comment for "How Can I Determine If A Javascript Variable Is Defined In A Page?"