How can I determine if a JavaScript variable is defined in a page?

Javascript

Javascript Problem Overview


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.

Javascript Solutions


Solution 1 - Javascript

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

Solution 2 - Javascript

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

if ('undefined' !== typeof x) {

Solution 3 - Javascript

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 - Javascript

You can do that with:

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

Solution 5 - Javascript

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.

Solution 6 - Javascript

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();

Solution 7 - Javascript

try to use undefined

if (x !== undefined)

This is how checks for specific Browser features are done.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSSharmaView Question on Stackoverflow
Solution 1 - JavascriptSSharmaView Answer on Stackoverflow
Solution 2 - JavascriptAndrew HedgesView Answer on Stackoverflow
Solution 3 - JavascriptPablo CabreraView Answer on Stackoverflow
Solution 4 - JavascriptSébastien Grosjean - ZenCocoonView Answer on Stackoverflow
Solution 5 - JavascriptDagg NabbitView Answer on Stackoverflow
Solution 6 - JavascriptkamensView Answer on Stackoverflow
Solution 7 - JavascriptNick BerardiView Answer on Stackoverflow