Imagine your teacher asks the class to write out the 7 times table, all the way
to
When you know in advance exactly how many times you want to repeat — twelve
times, a hundred times, once for every day of the week — you reach for a
count-controlled loop. It has a little counter that starts at some
number, counts up by one each go, and stops when it has run the right number of times. In TypeScript
(and lots of other languages) this loop is written with the keyword for, so people
often just call it a for loop.
for loop
Every count-controlled loop has the same three little parts, all squeezed into the brackets after
for, separated by semicolons:
let i = 0 creates the counter (traditionally named
i, for index) and sets it going from i < n is a
i++ adds i = i + 1).
Everything inside the curly braces { } is the body — the work that
runs once per count. Watch a counter climb below, then we'll write some real loops.
Here is the whole idea in miniature. Instead of writing console.log five times, we
write it once inside a loop that runs five times. Press Run:
Notice the counter i takes the values i < 5. Starting at
Now think about how much work the loop saved. Ten passes? Change one number. A thousand passes? Still change one number. The loop replaces copy-pasting — and unlike copy-paste it never mistypes a line.
Loops shine when you want to use the counter, not just repeat blindly. Here we print the
numbers i <= 10:
There are two fair ways to count to ten: start at i < 10, or start at i <= 10. Both
run the body ten times — you just pick whichever makes your numbers come out right.
Back to that i runs from
table value to any number you like and
Run it again:
One tiny loop can print the
A loop can also add things up as it goes. We keep a running total in a variable
(often called an accumulator) that starts at
The computer happily added a hundred numbers in a blink. Try changing n to
Legend has it that when the mathematician Carl Friedrich Gauss was a boy, his
teacher told the class to add up every number from
A for loop is the right tool when you know the number of repeats before
the loop starts — "do this 12 times", "once for each of the 30 pupils". But sometimes you don't
know the count in advance: "keep asking for a password until it's correct", or "keep rolling the dice
until you get a six". Those are condition-controlled loops (usually a
while loop), and they're a story for
The most famous loop bug in all of programming is the off-by-one error — running
the loop one time too many, or one time too few. It almost always comes down to two small choices:
where you start (< or <=).
Suppose you want to print exactly five stars. This loop prints six, because
starting at <= lets
i take the values
Two safe combinations both give exactly
i < n, ori <= n.
Mixing them up (start at <=) is the classic
off-by-one. When a loop does one too many or one too few, this is the first thing to check.