What the for loop is for
Counting loops written with while need the starting value, the condition and the update in three different places. The classic for loop puts all three in the header, on one line, so you can see at a glance how the loop starts, when it continues and how it moves. That is why it is the usual choice when you know how many times to repeat something, or when you walk through a range of numbers.
The syntax
for (initialization; condition; iteration) {
// statements to repeat
}
The three parts, separated by semicolons, run at different moments:
- Initialization runs once, before anything else. It usually declares the loop variable.
- Condition is checked before every pass, the first one included. When it is true, the body runs. When it is false, the loop ends.
- Iteration runs after every pass of the body, then the condition is checked again. It usually moves the loop variable.
Tracing a loop
Here is a loop that prints a message four times:
for (let i = 0; i < 4; i++) {
console.log("Hello world!");
}
The order of events is:
let i = 0creates the variable, once.- Is
0 < 4? Yes. Run the body, theni++makesiequal to 1. - Is
1 < 4? Yes. Run the body, thenibecomes 2. - Is
2 < 4? Yes. Run the body, thenibecomes 3. - Is
3 < 4? Yes. Run the body, thenibecomes 4. - Is
4 < 4? No. The loop ends.
The body ran for i equal to 0, 1, 2 and 3, which is four times. Starting at 0 and using i < n is the standard way to repeat something exactly n times, and the same shape appears again whenever you loop over the positions of an array.
TypeScript details
letkeeps the variable inside the loop. A variable declared withletin the header exists only for the loop. Readingiafter the closing brace is a compile error: the compiler reports that it cannot find the namei.- The type is inferred. In
let i = 0the compiler knows thatiis anumber, so you do not have to writelet i: number = 0. Both are correct. i++means "add 1 toi". It is the usual way to write the update.i += 1does the same.- Every part is optional. You may leave a part empty, but the semicolons must stay. A header written as
for (;;)has no condition, which counts as always true, and it loops until abreakor areturnstops it.
The exercise
The task is to print "I promise to learn coding." five times. The message is the same on every pass, so the loop variable only has to make the body run five times. The two steps are:
- Write the loop header. Start
iat 0, continue whilei < 5, and add 1 after each pass. The values ofiare 0, 1, 2, 3 and 4, which is five values. - Put the print statement in the body.
console.logwith the message runs once per pass, so the message appears five times, each on its own line.
The solution in TypeScript
for (let i = 0; i < 5; i++) {
console.log("I promise to learn coding.");
}
The loop variable i is not used inside the body. It is there only to count the passes, and that is perfectly normal.
Common mistakes
- Commas instead of semicolons. The three parts of the header are separated by semicolons.
for (let i = 0, i < 5, i++)does not compile. - Off by one. Writing
i <= 5with a start of 0 prints six times, andi < 4prints four times. To repeat five times from 0, usei < 5. - A condition that is never false. Writing
i > 0withi++from 0 gives a loop that runs 0 times. Writingi >= 0withi++gives a loop that never ends. Read the header aloud: "start at 0, keep going whileiis below 5, add 1 each time." - A semicolon after the header.
for (...);makes an empty loop, and the block below it then runs once, outside the loop. - Changing
iinside the body. The iteration step still runs afterwards, so extra changes make the count hard to follow and can cause infinite loops.
Key takeaways
- A
forheader holds the initialization, the condition and the iteration, separated by semicolons. - Initialization runs once, the condition runs before each pass, and the iteration runs after each pass.
for (let i = 0; i < n; i++)runs its body exactlyntimes.- A variable declared with
letin the header cannot be used after the loop.