How to check a not-defined variable in JavaScript

How to check a not-defined variable in JavaScript

I wanted to check whether the variable is defined or not. For example, the following throws a not-defined error
alert( x );

How can I catch this error?

Solutions/Answers:

Solution 1:

In JavaScript, null is an object. There’s another value for things that don’t exist, undefined. The DOM returns null for almost all cases where it fails to find some structure in the document, but in JavaScript itself undefined is the value used.

Second, no, there is not a direct equivalent. If you really want to check for specifically for null, do:

if (yourvar === null) // Does not execute if yourvar is `undefined`

If you want to check if a variable exists, that can only be done with try/catch, since typeof will treat an undeclared variable and a variable declared with the value of undefined as equivalent.

But, to check if a variable is declared and is not undefined:

if (typeof yourvar !== 'undefined') // Any scope

Beware, this is nonsense, because there could be a variable with name undefined:

if (yourvar !== undefined)

If you want to know if a member exists independent but don’t care what its value is:

if ('membername' in object) // With inheritance
if (object.hasOwnProperty('membername')) // Without inheritance

If you want to to know whether a variable is truthy:

if (yourvar)

Source

Solution 2:

The only way to truly test if a variable is undefined is to do the following. Remember, undefined is an object in JavaScript.

if (typeof someVar === 'undefined') {
  // Your variable is undefined
}

Some of the other solutions in this thread will lead you to believe a variable is undefined even though it has been defined (with a value of NULL or 0, for instance).

Solution 3:

Technically, the proper solution is (I believe):

typeof x === "undefined"

You can sometimes get lazy and use

x == null

but that allows both an undefined variable x, and a variable x containing null, to return true.

Solution 4:

An even easier and more shorthand version would be:

if (!x) {
   //Undefined
}

OR

if (typeof x !== "undefined") {
    //Do something since x is defined.
}

Solution 5:

I’ve often done:

function doSomething(variable)
{
    var undef;

    if(variable === undef)
    {
         alert('Hey moron, define this bad boy.');
    }
}

Solution 6:

You can also use the ternary conditional-operator:

var a = "hallo world";
var a = !a ? document.write("i dont know 'a'") : document.write("a = " + a);
//var a = "hallo world";
var a = !a ? document.write("i dont know 'a'") : document.write("a = " + a);