Why does this "for" with double condition give infinite loop?

Asked

Viewed 148 times

0

According to this documentation of the loop for in Javascript, the second expression is a condition:

for ([inicialização]; [condição]; [expressão final])
   declaração

If I make a condition like this:

var c = 0;
var d = 3;
for(let x = 0; x < 3 || c < d; x++){
   console.log(x);
}

Gives infinite loop and locks the browser tab (I did not put a tweaking snippet so).

Now, if the condition uses the operator || which is "one thing or the other", i.e., the x < 3 should not be enough to finalize the loop when x is equal to 3 ignoring the other unchanging condition c < d and not give an infinite loop? What would be the technical explanation for this?

  • 5

    It makes no sense. The condition is to CONTINUE, not to stop. EITHER OR continue the loop. Honestly, that sounds like a basic documentation problem. Even the for is irrelevant to the question, that || will give true in if, while, ternary, etc. In other words, it would have no reason to be different from that. It would be something like "If I do var x = 1, x value 1. What is the technical explanation for this? - A: it is the expected behavior, it would not have to be different"

1 answer

7


The infinite loop happens because, in this case, the [condição] of the loop for will always be true.

Like c (0) at all times will be minor that d (3), the operator’s second operation OR || will always be true. This means that, even if eventually (after the third iteration), the first operand (x < 3) be evaluated as false, the loop will continue running.

As stated in the documentation:

If this expression is evaluated for true, statement will be executed.

And that’s exactly what happens, since:

console.log(true || true); // true
console.log(false || true); // true

Browser other questions tagged

You are not signed in. Login or sign up in order to post.