Search code examples
javascripthtmlfor-loopvariablesclient-side-scripting

Why won't or statement work in a for loop?


I was looking at the w3schools JavaScript tutorial and found something that made it crash. I was trying to replace the break statement with the same thing in the second statement of the for loop. This isn't really a problem, I just think there's something I'm not understanding.

This was the code they had:

<html>
<body>

<h2>JavaScript Loops</h2>

<p>A loop with a <b>break</b> statement.</p>

<p id="demo"></p>

<script>
let text = "";
for (let i = 0; i < 10; i++) {
  if (i === 3) { break; }
  text += "The number is " + i + "<br>";
}

document.getElementById("demo").innerHTML = text;
</script>

</body>
</html>

And it works perfectly fine. Then I changed it to this:

<html>
<body>

<h2>JavaScript Loops</h2>

<p>A loop with a <b>break</b> statement.</p>

<p id="demo"></p>

<script>
let text = "";
for (let i = 0; i < 10 || i !== 3; i++) {
  text += "The number is " + i + "<br>";
}

document.getElementById("demo").innerHTML = text;
</script>

</body>
</html>

Then, if I run it, the webpage crashes. if I change the or(||) to an and(&&), then it works. Why is this?


Solution

  • i < 10 || i !== 3 will be always true since either i < 10 OR i >= 10 and thus i !== 3. So the loop will continue forever and hang the browser.

    The second part of the for statement is a condition:

    for (initialization; condition; afterthought)
    

    It's evaluated in the begining of each cycle and if true the loop will go on with the next cycle. Making it always true makes the loop running forever.