A valid (yet weird looking) for loop!

I recently posted the following poll to Twitter about what the output of this for loop will be:

The for loop (repeated from the tweet with color formatting) is this:

let i = 0;
let yay = true;

for (; yay;) {
    if (i == 3) {
      yay = false;
    } else {
      i++;
      document.writeln("weird");
    }
}

What will the output be? The answer is weird weird weird. The full explanation for why can be found in the For, While, and Do…While Loops tutorial.

The key is in this diagram that describes the general structure of a for loop:

The only thing a for loop truly needs to run properly is for the condition value to eventually return false. If the condition value was always true, our loop would run forever and freeze our browsers.

In our example, the condition is the value of the yay variable. Our loop runs until yay is set to false, and that happens when i is equal to 3. By the time that happens, the word weird will have been printed to the screen three times.

In real life, please don’t write for loops like this. For something fun and irritating (at the same time), loops like this are totally cool :cocktail:

Cheers,
Kirupa :smiling_imp:

No option for [Violation] Avoid using document.write(). ?

:upside_down_face:

1 Like