Search code examples
javascriptcomparison-operators

Simplify boolean expression containing potentially undefined variables


I have a boolean expression defined as such :

const actif =
  this.props.configuration &&
  this.props.configuration.puissance &&
  this.props.configuration.puissance > 0

Depending on the component, this.props. might or not have configuration and configuration might or not have puissance. that’s why I need to do all these verifications.

using { has } from 'lodash', I have been able to simplify a bit already :

const actif =
      has(this.props.configuration, 'puissance') &&
      this.props.configuration.puissance > 0

But that’s not really satisfying either.

I tried something else. I know that JS allows you to do something like this :

(undefined || 4) === 4

which is true. unfortunately,

(this.props.configuration.puissance || undefined ) > 0 

still gives me Cannot read property 'puissance' of undefined

Is there a simple way to do this comparison without having to check the entire tree of the object ? (and stop going any further in the tree if any step is undefined ?)


Solution

  • Since it sounds like you're using lodash already, how about using lodash's _.get() function?

    const actif = _.get(this.props, "configuration.puissance", 0) > 0;
    

    There is a proposal for an optional chaining property in JavaScript, but it's not made it into the language yet. When/if it does, you could do something like this:

    const actif = this.props?.configuration?.puissance || 0 > 0;