Ateev Chopra
Ateev Chopra

Reputation: 1026

"Cannot read property .. of null" after checking for undefined object

I have an object that I need to check if it is defined. Also, I also want to check if a property of that object is true or false.

So what I want is

if ((typeof myVar !== 'undefined') && (myVar.isMale === false)) {
     // Do something 1
 }
 else{
      // Do something 2
 }

But this logic gives me error

Uncaught TypeError: Cannot read property 'isMale' of null 

What will be the best login to handle this condition ?

Thanks !

Upvotes: 1

Views: 10385

Answers (2)

Md. Jahid Hossain
Md. Jahid Hossain

Reputation: 1121

using optional chaining operator (?.) to access the property isMale of the object myVar. optional chaining allows safe access to the properties of an object, even if the object itself might be null or undefined rather than causing an error.

if (myVar?.isMale) {
  // Do something 2
} else {
  // Do something 1
}

Upvotes: 0

RobG
RobG

Reputation: 147403

You need to test further, either by exclusion:

if (typeof myVar != 'undefined' && myVar && myVar.isMale === false) {

or by inclusion:

if (typeof myVar == 'object' && mVar && myVar.isMale === false) {

but there are objects that return values other than "object" with typeof tests (e.g. host objects may and Function objects do).

or by explicit conversion:

if (typeof myVar != 'undefined' && Object(myVar).isMale === false) {

Edit

The additional && myVar test is to catch NaN and null which pass the typeof test.

Upvotes: 6

Related Questions