JS why FOR LOOP not iterating when condition is A&&B but works when B&&A (A==B==true)

Viewed 56

This is my first question so hello everyone!

I wanted to write condition in way to terminate loop ASAP.

Loop which doesn`t work but should terminate loop faster:

for (
      let i = 0;
      transactionsSortedByTime[i].unixTime <= unixEndTime && i < listLength;
      i++
    ) {}

Loop which works:

for (
      let i = 0;
       i < listLength && transactionsSortedByTime[i].unixTime <= unixEndTime;
      i++
    ) {}

Till now I was certain that results of A&&B and B&&A are the same but terminates with false result in different time (when one of them {A or B} is false).

My question is why second one loop iterates properly while first one doesn`t.

2 Answers

In your case, A & B is not same as B & A because in first code snippet, you are accessing the i'th index of transactionsSortedByTime array before checking if i is less then listLength. Doing this will give you undefined when i < listLength is false.

So i < listLength should be written before transactionsSortedByTime[i].unixTime <= unixEndTime to make sure your code doesn't tries to access an index that is out of bounds of the transactionsSortedByTime array.

Just add (), the loop structure apparently takes the bool value of the first expression, to solve this you must add parentheses, so that your expression takes the value of your && operator:

for (
  let i = 0;
  (transactionsSortedByTime[i].unixTime <= unixEndTime && i < listLength);
  i++
) {}
Related