What up, homeslice? Glad you found this blog series about JavaScript Twitter quizzes! This week is a funny snippet around the loop-manipulating key-words break
and continue
. Get ready for some serious trickery!
Snippet of the Week
This week's snippet is from fullstack_learning_path:
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 of the values having no remainder when divided by 3 (% 3
). In case 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
. In case the index can be divided by three without having a remainder, the expression is false. It's true for 1, 2, 4, 5, 7, 8 in this context, to be even more exact.
Let's examine what happens then: continue
is called. This key-word 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. In case the index holds the value 7, the loop breaks. break
is a key-word 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
reached 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.
Snippet Summary
- Trickery: creating logically unreachable-code
-
Key Learning: what
continue
andbreak
does - Further Reading:
Top comments (0)