Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript check if object property exists, even when object is undefined

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/

like image 768
Don P Avatar asked Dec 11 '22 04:12

Don P


2 Answers

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.

like image 50
Alnitak Avatar answered Feb 12 '23 11:02

Alnitak


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

like image 37
Mish Schmid Avatar answered Feb 12 '23 10:02

Mish Schmid