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?
The error is telling you that
x
doesn’t even exist! It hasn’t been declared, which is different than being assigned a value.If you declared
x
, you wouldn’t get an error. You would get an alert that saysundefined
becausex
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.This is checking the type of the value stored in
x
. It will only returnundefined
whenx
hasn’t been declared OR if it has been declared and was not yet assigned.