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 cat
The error is telling you that x
doesn’t even exist! It hasn’t been declared, which is different than being assigned a value.
var x; // declaration
x = 2; // assignment
If you declared x
, you wouldn’t get an error. You would get an alert that says undefined
because x
exists/has been declared but hasn’t been assigned a value.
To check if the variable has been declared, you can use typeof
, any other method of checking if a variable exists will raise the same error you got initially.
if(typeof x !== "undefined") {
alert(x);
}
This is checking the type of the value stored in x
. It will only return undefined
when x
hasn’t been declared OR if it has been declared and was not yet assigned.
The void operator returns undefined
for any argument/expression passed to it. so you can test against the result (actually some minifiers change your code from undefined
to void 0
to save a couple of characters)
For example:
void 0
// undefined
if (variable === void 0) {
// variable is undefined
}
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).
I've often done:
function doSomething(variable)
{
var undef;
if(variable === undef)
{
alert('Hey moron, define this bad boy.');
}
}
Just do something like below:
function isNotDefined(value) {
return typeof value === "undefined";
}
and call it like:
isNotDefined(undefined); //return true
isNotDefined('Alireza'); //return false
The accepted answer is correct. Just wanted to add one more option. You also can use try ... catch
block to handle this situation. A freaky example:
var a;
try {
a = b + 1; // throws ReferenceError if b is not defined
}
catch (e) {
a = 1; // apply some default behavior in case of error
}
finally {
a = a || 0; // normalize the result in any case
}
Be aware of catch
block, which is a bit messy, as it creates a block-level scope. And, of course, the example is extremely simplified to answer the asked question, it does not cover best practices in error handling ;).