Loops
8 min · JavaScript
Repeat work without writing it out a hundred times.
Enemy 1 of 5
A loop repeats a block of code so you don't have to write it out by hand over and over. If you ever catch yourself copy-pasting a line with only a small tweak each time, that's usually a sign a loop belongs there instead.
A for loop repeats a block and has three parts, all inside the parentheses and separated by semicolons: a starting point (let i = 0), a condition to keep going (i < 3), and a step to run after each pass (i++, which adds 1 to i). JavaScript checks the condition before every iteration — the moment it's false, the loop stops immediately, without running the body one more time.
This counts i from 0 while i is less than 3, adding 1 each time — so it runs exactly three times, printing 0, 1, and 2. Getting the condition slightly wrong (using <= instead of <, for instance) is an easy way to end up running one iteration too many, a classic off-by-one bug.
Loading editor...