admin管理员组

文章数量:1356591

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 !

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 !

Share Improve this question edited Aug 18, 2014 at 6:57 user2864740 62.1k15 gold badges158 silver badges227 bronze badges asked Aug 18, 2014 at 6:43 Ateev ChopraAteev Chopra 1,0263 gold badges16 silver badges32 bronze badges 4
  • 2 'undefined' and 'null' are two different things. you are checking if the object is 'undefined' not when it is null – Prabhu Murthy Commented Aug 18, 2014 at 6:44
  • first check if myVar is undefined, then, once you know it is not undefined, check for its properties. In this way, if typeof myVar is undefined it can't have any property, therefore your if will always fail. – briosheje Commented Aug 18, 2014 at 6:44
  • after checking 'undefined' you should check for null, if ( typedef myVar != 'undefined' && myVar !== null && myVar.isMale === false) { // do something} – Sadegh Commented Aug 18, 2014 at 6:47
  • Ofcourse I thought of it. But Can you express this in if else conditions. I need to have both conditions to Do Something 1. Else it should go to Do Something 2 – Ateev Chopra Commented Aug 18, 2014 at 6:48
Add a ment  | 

2 Answers 2

Reset to default 6

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.

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
}

本文标签: javascriptquotCannot read propertyof nullquot after checking for undefined objectStack Overflow