0

this is blowing up

if (myObject.myKey.myThing){

}

cannot read myThing of undefined

how can this be written in a way that if it is defined it goes into the if block, and if it not it does not?

eisbehr
  • 12,243
  • 7
  • 38
  • 63
donut
  • 343
  • 2
  • 7
  • 15
  • Hopefully in future we will be able to use optional chaining https://github.com/tc39/proposal-optional-chaining – justMe Aug 07 '18 at 12:00

2 Answers2

0

Add another check to see if myObject.myKey exists -

if (myObject.myKey && myObject.myKey.myThing){

}
Rishikesh Dhokare
  • 3,559
  • 23
  • 34
0

you would use the hasOwnProperty method, like so

if (myObject.hasOwnProperty('myKey')) {
   ...
}

You would want to use this as opposed to just checking the value of the keys because then if the value of that key is a false equivalent value your code won't run

codeWonderland
  • 297
  • 1
  • 11