I want to check if an object exists, and has a property. Currently I get a "myObject is undefined" error that stops the check.
How can I make the following still work correctly even when myObject may not exist?
if (myObject.myProperty) {
...
} else {
...
}
I am trying to just even check if a object / variable exists but getting an error:
if (foo) { console.log('hello'); }
gives the error Uncaught ReferenceError: foo is not defined. Here is a jsfiddle http://jsfiddle.net/cfUss/
I've been suprised not to find this helpful function in basic Javascipt interface. Below is a helper function I often use in my projects. It checks if the value of the final chain element is reachable without an error "can't get ... of undefined":
Try:
This code enters the body of the
if
block ifmyObject
exists and also hasmyproperty
. IfmyObject
doesn't exist for some reason, the&&
short-circuits and does not evaluatedmyObject.myProperty
.You can use the "short circuit"
&&
operator:If
myObject
is "falsey" (e.g. undefined) the&&
operator won't bother trying to evaluate the right-hand expression, thereby avoiding the attempt to reference a property of a non-existent object.The variable
myObject
must have course already have been declared, the test above is for whether it has been assigned a defined value.