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 catch this error?
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 catch this error?
An even easier and more shorthand version would be:
OR
I use a small function to verify a variable has been declared, which really cuts down on the amount of clutter in my javascript files. I add a check for the value to make sure that the variable not only exists, but has also been assigned a value. The second condition checks whether the variable has also been instantiated, because if the variable has been defined but not instantiated (see example below), it will still throw an error if you try to reference it's value in your code.
Not instantiated -
var my_variable;
Instantiated -var my_variable = "";
You can then use a conditional statement to test that the variable has been both defined AND instantiated like this...
or to test that it hasn't been defined and instantiated use...
The
void
operator returnsundefined
for any argument/expression passed to it. so you can test against the result (actually some minifiers change your code fromundefined
tovoid 0
to save a couple of characters)For example:
I've often done:
I often use the simplest way:
EDIT:
Without initializing the variable, exception will be thrown "Uncaught ReferenceError: variable is not defined..."
In JavaScript,
null
is an object. There's another value for things that don't exist,undefined
. The DOM returnsnull
for almost all cases where it fails to find some structure in the document, but in JavaScript itselfundefined
is the value used.Second, no, there is not a direct equivalent. If you really want to check for specifically for
null
, do:If you want to check if a variable exists, that can only be done with
try
/catch
, sincetypeof
will treat an undeclared variable and a variable declared with the value ofundefined
as equivalent.But, to check if a variable is declared and is not
undefined
:If you know the variable exists, and want to check whether there's any value stored in it:
If you want to know if a member exists independent but don't care what its value is:
If you want to to know whether a variable is truthy:
Source