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/
You can use the "short circuit" &&
operator:
if (myObject && myObject.myProperty) {
...
}
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.
You can use the optional chaining operator ?.
to keep things succinct:
if (myObject?.myProperty) { ... }
which is equal to the a bit more verbose
if (myObject && myObject.myProperty) { ... }
It comes in very handy especially for deeply nested objects.
It's currently (September 2019) a ECMAScript stage 3 proposal but things are looking promising that this feature will become officially available. For the time being, you can already start using it via the respective Babel plugin: https://babeljs.io/docs/en/babel-plugin-proposal-optional-chaining
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With