Destructuring Tweets – Episode 11 – Continue to Break
Glad you found this blog series about JavaScript Social Media quizzes! This week is a funny snippet around the loop-manipulating keywords break
and continue
. Get ready for some serious trickery!
The Snippet
for (var i = 1; i < 10; ++i) {
if (i % 3) {
continue;
}
if (i == 7) {
break;
}
console.log(i);
}
The snippet features a for-loop initializing the variable i
with 1. Said gets incremented by 1 until it's 9 (< 10
). To put it simply: we count from 1 to 9.
In the loop, there are two checks before printing the current index to the console — the first tests whether modulo 3 returns a truthy value, which means everything except 0. In that case, continue
gets executed.
If not, the snippet further validates whether the current index holds 7. In case it does, break
is executed.
The Output
Okay, that one is a bit of a brain-fuck. On first thought, you might conclude it'll log 3 and 6. Since the loop breaks on 7, right? However, it will still also print 3, 6, and 9! All three values have no remainder when divided by 3 (% 3
). If you are still or even more confused, worry not and jump right to the next chapter.
The Analysis
So, we already figured the loop is counting from 1 to 9. Let's focus on the first check, i % 3
. It will always be true if it does not result in 0
. The expression is false if the index can be divided by three without having a remainder. It's true for 1, 2, 4, 5, 7, and 8 in this context, to be even more exact.
Let's examine what happens then: continue
is called. This keyword tells the loop to skip the rest of its body and move to the next iteration. Meaning the console.log
at the bottom is never reached. Or the other way around, only 3, 6, and 9 are logged.
Now let's focus on the second if-statement. If the index holds the value 7, the loop breaks. break
is a keyword telling the loop to stop with everything. It skips the rest of its body and will not iterate further, continuing with whatever is next in the sequence.
That's why this snippet is so funny. It tricks you into believing 9 will not print since it stops after i
reaches 7. Well, as we know, this is not the case. And by now, you probably already figured also why. The second statement is, just as console.log(i)
, only reached by 3, 6, and 9. These numbers are not 7 🤯, thus making the body of the second if-statement unreachable code! break
is never executed.