Dancer
Dancer

Reputation: 17651

Chaining If conditions with && operator

I have the following code - which carries out a variety of state checks:

CheckValStates= () => {

  _stateCheck = val => {
    if (!val || val == '' ) {
      return true;
    }
    return false;
  };


if (
      this._stateCheck(this.state.arReason) ||
      this._stateCheck(this.state.handoverType) ||
      (this.state.handoverType === 'CUSTOMER' &&
        this._stateCheck(this.state.staffHandoverDeets)) ||
      (this.state.handoverType === 'GUARD' &&
        this._stateCheck(this.state.keyStatus) &&
        this._stateCheck(this.state.staticOfficerHandover))
    ) {
     return true;
    }

  return false;
  };
}

I was having issues with the following line:

(this.state.handoverType === 'GUARD' &&
        this._stateCheck(this.state.keyStatus) &&
        this._stateCheck(this.state.staticOfficerHandover))
)

Returns true if only the first 2 elements are true - the 3rd check (this._stateCheck(this.state.staticOfficerHandover)) is ignored. I was expecting all three checks to match for a true result.

If i replace that chained statement with -

if (


      this._stateCheck(this.state.arReason) ||
      this._stateCheck(this.state.handoverType) ||
      (this.state.handoverType === 'CUSTOMER' &&
        this._stateCheck(this.state.staffHandoverDeets)) ||

      (this.state.handoverType === 'GUARD' && this._stateCheck(this.state.keyStatus) || this.state.handoverType === 'GUARD' && this._stateCheck(this.state.staticOfficerHandover) )
    ) 

it carries out the check as expected. I'd like to understand why.

Upvotes: 0

Views: 85

Answers (1)

user15568835
user15568835

Reputation:

I think that your function _stateCheck is not perfect : some values can cause problem.

stateCheck(null) // true
stateCheck(undefined) // true
stateCheck("") // true
stateCheck({}) // false
stateCheck([]) // true  - possible problem
stateCheck(true) // false
stateCheck(false) // true - possible problem
stateCheck(0) // true - possible problem
stateCheck(-10) // false
stateCheck(10) // false

If this.state.staticOfficerHandover was a problematic value, stateCheck will send true

Example:

const stateCheck = val => {
    if (!val || val == '' ) {
      return true;
    }
    return false;
  };


const state = {
    handoverType: "GUARD",
    keyStatus : "",
    staticOfficerHandover: true,
}

const condition = (state.handoverType === 'GUARD' &&
 stateCheck(state.keyStatus) &&
 stateCheck(state.staticOfficerHandover)
 )
console.log(condition); // false

state.staticOfficerHandover = false;
const condition2 = (state.handoverType === 'GUARD' &&
 stateCheck(state.keyStatus) &&
 stateCheck(state.staticOfficerHandover)
 )
 console.log(condition2); // true

Upvotes: 1

Related Questions