What a while loop does
A while loop repeats a block of statements for as long as a condition is true. Before every pass, the program evaluates the condition. If it is true, the body runs once and the program evaluates the condition again. If it is false, the loop ends and the program continues with the first statement after the closing brace.
The structure looks like this:
while (condition) {
instruction1;
instruction2;
}
You can think of it as an if statement that jumps back and asks its question again after the body.
A worked example
let count = 1;
while (count <= 3) {
console.log("I made a mistake");
count++;
}
console.log("Finished!");
This prints:
I made a mistake
I made a mistake
I made a mistake
Finished!
The trace below shows what happens, with the loop limited to three passes:
countis created with the value 1.- Is
1 <= 3? Yes. Print the message.count++makes it 2. - Is
2 <= 3? Yes. Print the message.countbecomes 3. - Is
3 <= 3? Yes. Print the message.countbecomes 4. - Is
4 <= 3? No. The loop ends. - The program prints
Finished!, once.
The condition is checked one more time than the body runs. Three passes need four checks, and the last check is the one that fails.
The three parts every counting loop needs
- Initialization. A variable declared before the loop, such as
let counter: number = 1;. Uselet, because its value will change. - Condition. The expression in the parentheses, such as
counter <= 5. It decides whether another pass happens. - Update. A statement in the body that moves the variable toward making the condition false, such as
counter++, which adds 1.
If the update is missing, the condition never changes, and the loop never ends. This is an infinite loop.
A condition can be false from the start
If the condition is false the first time it is checked, the body never runs at all:
let n: number = 10;
while (n < 5) {
console.log("never printed");
}
console.log("skipped, n is", n);
skipped, n is 10
The exercise
The task is to print I promise to learn coding. five times, this time with a loop instead of five copies. The lesson builds it in four steps:
- Declare the counter.
let counter: number = 1;. The: numberannotation states the type; TypeScript would infer it anyway. It must belet, since the loop changes it. - Write the loop with its condition.
while (counter <= 5)is true for the values 1, 2, 3, 4 and 5, which gives five passes. - Print inside the body. One
console.logwith the sentence. - Update the counter.
counter++inside the body. Without it,counterstays 1 and the loop prints forever.
let counter: number = 1;
while (counter <= 5) {
console.log("I promise to learn coding.");
counter++;
}
After the fifth pass, counter is 6, the condition 6 <= 5 is false, and the loop ends.
Tracing the exercise
Writing down the value of the counter at the moment of each check is the quickest way to find an off-by-one error. For the loop above, the checks go like this:
| Check | counter | counter <= 5 | Result |
|---|---|---|---|
| 1st | 1 | true | print, counter becomes 2 |
| 2nd | 2 | true | print, counter becomes 3 |
| 3rd | 3 | true | print, counter becomes 4 |
| 4th | 4 | true | print, counter becomes 5 |
| 5th | 5 | true | print, counter becomes 6 |
| 6th | 6 | false | loop ends |
Five true checks give five lines of output. This is why the number you compare against, here 5, is also the number of repetitions when the counter starts at 1 and the condition uses <=.
Common mistakes
- Forgetting the update. The classic bug: the program never finishes.
- Off-by-one conditions. Starting at 1 with
< 5gives four passes, and starting at 0 with<= 5gives six. Count the values the counter takes. - Using
constfor the counter.counter++then fails. The compiler reports that it cannot assign to a constant, and at run time the JavaScript throws aTypeError. - Putting the update outside the braces. It then runs after the loop, which is never reached.
- A semicolon after the header.
while (counter <= 5);makes the semicolon the loop's whole body. That body is empty and changes nothing, so the loop never ends, and the braces below it are only a separate block.
Key takeaways
while (condition) { ... }repeats its body as long as the condition is true, checking before every pass.- A counting loop needs a starting value, a condition and an update.
- If the condition starts false, the body never runs.
- Always make sure something in the loop moves the condition toward false.