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,
- it hasn't been defined
- it has been defined and has the value
undefined
, or - 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");
}