I wanted to check whether the variable is defined or not.
eg
alert( x );
Throws a not defined error
How can I catch this error?
I wanted to check whether the variable is defined or not.
eg
alert( x );
Throws a not defined error
How can I catch this error?
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, they are not directly equivalent. If you really want to check for null, do:
if (null == yourvar) // with casting
if (null === yourvar) // without casting
If you want to check if a variable exist
if (typeof yourvar != 'undefined') // Any scope
if (window['varname'] != undefined) // Global scope
if (window['varname'] != void 0) // Old browsers
If you know the variable exists but don't know if there's any value stored in it:
if (undefined != yourvar)
if (void 0 != yourvar) // for older browsers
If you want to know if a member exists independent of whether it has been assigned a value or not:
if ('membername' in object) // With inheritance
if (object.hasOwnProperty('membername')) // Without inheritance
If you want to to know whether a variable autocasts to true:
if(variablename)
I probably forgot some method as well...
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.
Even easier and more shorthand version would be:
if( !x ){
//undefined
}
OR
if( typeof x != "undefined" ){
//do something since x is defined.
}
try {
if (myVar) {}
} catch (err) {
var myVar = "";
}
Source: http://dmartin.org/weblog/javascript-checking-whether-a-variable-exists
I've often done:
function doSomething(variable)
{
var undef;
if(variable == undef)
{
alert('Hey moron, define this bad boy.');
}
}
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 var === '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).