Another way to do this is to use the typeof
operator.
In JS if a variable has been declared but not set a value, such as:
var x;
Then x
is set to undefined
so you can check for it easily by:
if(x) //x is defined
if(!x) //x is undefined
However if you try to do if(x)
on a variable that hasn't even been declared, you'll get the error you allude to in your post, "ReferenceError: x is not defined".
In this case we need to use typeof
- MSDN Docs - to check.
So in your case something like:
if(typeof jsonObject !== "undefined") {
//jsonObject is set
if(jsonObject.errorMessage) {
//jsonObject set, errorMessage also set
} else {
//jsonObject set, no errorMessage!
}
} else {
//jsonObject didn't get set
}
This works because if you have a variable set to an empty object, x={}
, and try to get at a variable within that object that doesn't exist, eg x.y
, you get undefined
returned, you don't get a ReferenceError.
Be aware that the typeof
operator returns a string denoting the variable type, not the type itself. So it would return "undefined"
not undefined
.
Also, this very similar question on SO that could help you: How to check a not-defined variable in JavaScript
Hope this helps.
Jack.