2

I find I'm doing this, whereby I need to check that the preceeding variable is not undefined before checking the next one in the chain:

if( this.props.someVar && this.props.someVar.data ) {
    // do something with this.props.someVar.data ...
}

It would be ideal just to do this:

if( this.props.someVar.data ) {
    // This throws an error because I haven't checked if `this.props.someVar` exists beforehand.
}

Is there an easier/shorter way to so this, preferably using pure Javascript?

JoeTidee
  • 24,754
  • 25
  • 104
  • 149
  • 1
    Check if `someVar` is not undefined using `!= undefined` statement. – Oen44 Apr 13 '17 at 11:21
  • I know, not "pure" JS, but using [immutableJS](https://facebook.github.io/immutable-js/docs/#/) has the added benefit of having such great API as [getIn](https://facebook.github.io/immutable-js/docs/#/Collection/getIn) – thedude Apr 13 '17 at 11:23
  • try using `!!` with the parent then test the child – Ryad Boubaker Apr 13 '17 at 11:24

1 Answers1

-1

I hate that too. The easiest way is to use try catch like this

try {
    // do something with this.props.someVar.data
} catch (e) {
    if (e instanceof TypeError) {
       // TypeError happens when an object in the chain is undefined
    }
}
Mtihc
  • 191
  • 1
  • 12