# A valid (yet weird looking) for loop!

**URL:** <https://forum.kirupa.com/t/a-valid-yet-weird-looking-for-loop/640916>\
**Category:** Uncategorized\
**Created:** [October 23, 2019, 5:05am UTC](https://forum.kirupa.com/t/a-valid-yet-weird-looking-for-loop/640916 "2019-10-23T05:05:59Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![kirupa](https://yyz1.discourse-cdn.com/flex011/user_avatar/forum.kirupa.com/kirupa/32/11616_2.png) [@kirupa](https://forum.kirupa.com/u/kirupa)\
**Post date:** [October 23, 2019, 5:05am UTC](https://forum.kirupa.com/t/a-valid-yet-weird-looking-for-loop/640916/1 "2019-10-23T05:05:59Z")

</div>

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

> <https://twitter.com/kirupa/status/1185976626904911872>

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](https://www.kirupa.com/html5/loops_in_javascript.htm) tutorial.

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

 ![image](https://canada1.discourse-cdn.com/flex011/uploads/kirupa/original/2X/4/43cd8351650acbfba0471b0387f99f3bb8623e4f.png)

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 🍸

Cheers,  
Kirupa 😈

---

<div class="post-metadata">

**Author:** ![senocular](https://yyz1.discourse-cdn.com/flex011/user_avatar/forum.kirupa.com/senocular/32/7217_2.png) [@senocular](https://forum.kirupa.com/u/senocular)\
**Post date:** [October 23, 2019, 12:48pm UTC](https://forum.kirupa.com/t/a-valid-yet-weird-looking-for-loop/640916/2 "2019-10-23T12:48:23Z")

</div>

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

🙃
