Loops
Objectives
By the end of this chapter, you should be able to:
- Write a
forloop and explain all three of its parts - Write a
whileloop - Write a
do...whileloop, and explain when it behaves differently fromwhile
💡 Why this matters: Programs constantly need to repeat work: print every number in a range, keep asking for input until it’s valid, process one item after another. Loops let you write the repeated step once instead of copying it by hand.
The for Loop
A for loop is built for repeating something a known number of times. It has three parts, separated by semicolons, all sitting in the parentheses:
for (let i = 1; i <= 5; i++) {
console.log(i);
}
// 1
// 2
// 3
// 4
// 5
Each part does a specific job:
- Initializer (
let i = 1): runs once, before the loop starts. It usually declares a counter variable. - Condition (
i <= 5): checked before every iteration. As long as it’strue, the loop body runs. As soon as it’sfalse, the loop stops. - Increment (
i++): runs after every iteration, right before the condition is checked again.i++is shorthand fori = i + 1.
Tracing through the example: i starts at 1. The condition 1 <= 5 is true, so the body runs and logs 1. Then i++ makes i become 2. The condition 2 <= 5 is still true, so it logs 2. This keeps going until i becomes 6, where 6 <= 5 is false, and the loop stops without printing 6.
You can count down just as easily by changing the direction:
for (let i = 5; i >= 1; i--) {
console.log(i);
}
// 5
// 4
// 3
// 2
// 1
The while Loop
A while loop only has a condition. It keeps running its body as long as that condition stays true. You’re responsible for making sure something inside the loop eventually makes the condition false, otherwise it never stops.
let count = 1;
while (count <= 5) {
console.log(count);
count++;
}
// 1
// 2
// 3
// 4
// 5
This produces the same output as the first for loop. Use while when you don’t know in advance exactly how many times you’ll loop, for example, repeating something until a value crosses a threshold:
let savings = 100;
let years = 0;
while (savings < 200) {
savings = savings * 1.1;
years++;
}
console.log(years);
// 8
Here there’s no fixed count going in. The loop keeps doubling interest onto savings until it finally passes 200, however many years that takes.
The do...while Loop: Run the Body at Least Once
while checks its condition before running the body, so if the condition starts out false, the body never runs at all:
let stock = 0;
while (stock > 0) {
console.log("Selling one item.");
stock--;
}
console.log("Done.");
// Done.
stock is 0, so stock > 0 is false from the very first check, and "Selling one item." never prints.
A do...while loop checks its condition after running the body, so the body always runs at least once, no matter what:
let stock = 0;
do {
console.log("Selling one item.");
stock--;
} while (stock > 0);
console.log("Done.");
// Selling one item.
// Done.
Same starting value, same condition, but a different result: "Selling one item." prints exactly once here, because do...while runs the body first and only checks stock > 0 afterward. That single comparison, body-first versus condition-first, is the entire difference between the two loops, and it’s exactly why the two examples above print different things from the same starting state.
Reach for do...while specifically when the task must happen at least once before you can even check whether it should repeat. A countdown announcement is a good example: even a countdown that starts at 0 still needs to announce itself once before checking whether to count further.
let count = 0;
do {
console.log(count);
count--;
} while (count > 0);
// 0
With a plain while (count > 0), this would print nothing at all, because count starts at 0 and 0 > 0 is false immediately. The do...while guarantees that first announcement happens regardless.
Try It
- Write a
forloop that logs the numbers10down to1. - Write a
whileloop that starts a variabletotalat0and a variablenat1, addsntototaland incrementsneach time, stopping oncetotalis greater than20. Log the finaltotal. - Write two loops on a variable
ticketsset to0: onewhile (tickets > 0)and onedo...while (tickets > 0), each just logging"Ticket sold"and decrementingtickets. Confirm thewhileloop prints nothing and thedo...whileloop prints once.
Recap
for (initializer; condition; increment)is best when you know how many times to repeat.while (condition)checks before each run of the body, so the body might never run.do...whilechecks after each run of the body, so the body always runs at least once, useful when the first run has to happen before you can decide whether to repeat.
Next lesson: controlling a loop mid-run with break and continue, and nesting loops inside one another.