Loops
7 min · Dart
Repeat work without writing it out a hundred times.
Enemy 1 of 5
The for loop, piece by piece
This for loop sets i to 0, repeats while i is less than 3, and adds 1 each time, printing i on every pass. Press Run to see 0, 1, 2.
Why this works
Loops let a program repeat a block of code without you writing it out by hand for every repetition, which matters not just for saving typing, but because a change to repeated logic only needs to happen in one place instead of everywhere it was copy-pasted.
A for loop packs three pieces into its parentheses, separated by semicolons: an initializer that runs once before the loop starts (var i = 0), a condition checked before every iteration that keeps the loop going as long as it's true (i < 3), and an update that runs after every iteration (i++, shorthand for "increase i by 1"). Together they define exactly where the loop starts, when it stops, and how it advances.
The loop body runs once per iteration, with i taking a new value each time: first 0, then 1, then 2. The moment the condition i < 3 becomes false (once i reaches 3), the loop exits immediately, without running the body a fourth time.