Home » Javascript » How can I determine if a JavaScript variable is defined in a page? [duplicate]

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

Posted by: admin November 29, 2017 Leave a comment

Questions:

This question already has an answer here:

Answers:

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

Questions:
Answers:

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

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

Questions:
Answers:

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

Questions:
Answers:

You can do that with:

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

Questions:
Answers:

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.

Questions:
Answers:

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

Questions:
Answers:

try to use undefined

if (x !== undefined)

This is how checks for specific Browser features are done.