1

The code is as follows:

if(typeof state.getId().stateId !== "undefined") {
   console.log("Not undefined");
} else { 
   console.log("Undefined");
}

I keep getting this error: TypeError: Cannot read property of stateId

What am I doing wrong?

The issue with this was that state.getId() itself is undefined; and thus getting the property of stateId of state.getId() was the issue. This is not the same as the other question because a) it was not immediately clear that .getId().stateId was a property of undefined.

  • Possible duplicate of [Is there a standard function to check for null, undefined, or blank variables in JavaScript?](https://stackoverflow.com/questions/5515310/is-there-a-standard-function-to-check-for-null-undefined-or-blank-variables-in) – georgeawg Jul 31 '18 at 22:47

3 Answers3

0

try

if(!state || !state.getId() || typeof state.getId().stateId === "undefined") {
    console.log("Undefined");
} else {
    console.log("Not undefined");
}

If either state or the value returned from the call to getId are undefined then you will get an error. The short circuit or test will catch it and stop you trying to access a property on undefined which is what is causing your error.

Adrian Brand
  • 20,384
  • 4
  • 39
  • 60
  • Hey this was the right answer. The value returned from the call itself was undefined. Thanks! –  Aug 01 '18 at 19:00
0

check if state.getId() is truthy first then check his property

   if (state.getId() && state.getId().stateId !== "undefined") { 
         console.log("Not undefined");
   } else {
         console.log("Undefined");
   }
Muhammed Albarmavi
  • 23,240
  • 8
  • 66
  • 91
  • It is quite possible that the state object is what is undefined and causing the error. – Adrian Brand Jul 31 '18 at 23:06
  • if state in undefined you will get an error said cant read getId from undefined so the function return undefined , check if getId function has a return statement @AdrianBrand – Muhammed Albarmavi Aug 01 '18 at 07:38
  • Hey, this was also right; but Adrian answered first; thanks for your help! –  Aug 01 '18 at 19:01
0

Check if state exists, then check that state.getId is a function:

if (typeof state == "object" &&
    typeof state.getId == "function" ) {
   var id = state.getId();
   console.log("stateId=",id.stateId);
} else { 
   console.log("Undefined");
}

For more information, see

georgeawg
  • 48,608
  • 13
  • 72
  • 95