Test if a variable is defined in javascript?

Use the in operator.

'myVar' in window; // for global variables only

typeof checks will return true for a variable if,

  1. it hasn't been defined
  2. it has been defined and has the value undefined, or
  3. it has been defined but not initialized yet.

The following examples will illustrate the second and third point.

// defined, but not initialized
var myVar;
typeof myVar; // undefined

// defined, and initialized to undefined
var myVar = undefined;
typeof myVar; // undefined

if (typeof variable !== 'undefined') {
  // ..
}
else
{
     // ..
}

find more explanation here:

JavaScript isset() equivalent


You simply check the type.

if(typeof yourVar !== "undefined"){
  alert("defined");
}
else{
  alert("undefined");
}

Tags:

Javascript