How should I test if a variable is defined?
if //variable is defined
//do this
else
//do this
How should I test if a variable is defined?
if //variable is defined
//do this
else
//do this
if (typeof variable !== 'undefined') {
// ..
}
else
{
// ..
}
find more explanation here:
Use the in
operator.
'myVar' in window; // for global variables only
typeof
checks will return true for a variable if,
undefined
, orThe 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
You simply check the type.
if(typeof yourVar !== "undefined"){
alert("defined");
}
else{
alert("undefined");
}
You can use something like this
if (typeof varname !== 'undefined') {
// do this
} else {
// do that
}