Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

javascript

People also ask

How do you check if JavaScript variable is defined?

Use the typeof operator to check if a variable is defined or initialized, e.g. if (typeof a !== 'undefined') {} . If the the typeof operator doesn't return a string of "undefined" , then the variable is defined.

How do you know if a variable is undefined?

So the correct way to test undefined variable or property is using the typeof operator, like this: if(typeof myVar === 'undefined') .


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


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

You can do that with:

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


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.