Short-circuit evaluation with three variables

I wrote the following code, thinking it would fail to work because it would go like this: “if it is not running and the ID matches this one, execute the code” disregarding the cap on the break size:

if(x && xx&& xxx{
this.setState((state) => ({
  break: this.state.xxxx +1}))}

Much to my surprise, it worked. But I don´t really understand why. Wouldn´t it disregard the cap size because it would never be evaluated?

Why would it never be evaluated? You can string as many conditions as you like into an ifstatement.

The thing to note, when using either && (logical AND) or || (logical OR), is that they evaluate left-to-right. In the case of AND, they will evaluate until one returns false, at which point the if breaks (if one is false, they all evaluate as false). In the case of OR, they will evaluate until the first true is encountered (at which point, if one is true, all are true).

So stringing together three conditions works perfectly well. What it actually says is, “If isRunning is true, and the ID is break-increment and breakvar is under my cap value…” Which is perfectly valid. So long as ALL conditions are met, it will allow the loop to process.

1 Like

Thank you for the answer. I thought short-circuit would only evaluate two conditions. I see now that it will evaluate until one condition that doesn´t satisfy the criteria is met.

1 Like

Exactly right. I’ve strung together as many as a dozen conditions, which might, in retrospect, have been overkill – but you CAN do it. :wink:

1 Like