Suppose you need to send a reminder email to 500 customers. Writing the sending code 500 times would be absurd, and it would break the moment the list grew to 501. A loop solves this by running the same block once for each customer, however many there are. Each pass through the block is called an iteration.
Example
const guests = ["Ana", "Ben", "Chen"];
// for...of: runs once per item in the array
for (const name of guests) {
console.log(`Welcome, ${name}`);
}
// while: repeats until the condition turns false
let countdown = 3;
while (countdown > 0) {
console.log(countdown);
countdown--;
}
Choosing the right kind
- A for loop suits work with a known count, like "repeat 10 times" or "visit every index of an array". Most languages also offer a for-each form (
for...ofin JavaScript,for x in itemsin Python,foreachin PHP) that hands you each element directly. - A while loop tests its condition before each pass. It fits cases where the count is unknown in advance, such as reading input until someone types "quit".
- A do...while loop, available in JavaScript, Java, PHP and C, tests after each pass, so its body always runs at least once. Python has no do-while.
Infinite loops and early exits
If the test in a while loop never becomes false, the loop never ends and the program appears to freeze. Forgetting countdown-- above would do exactly that. Two keywords give finer control: break leaves the loop immediately, and continue skips the rest of the current iteration and moves on to the next.
Loops vs recursion
A function that calls itself can also repeat work, a technique known as recursion. Recursion suits nested structures such as folder trees, while loops tend to be simpler and lighter on memory for plain repetition.
Practise
- Experiment with each loop type in the JavaScript editor.
- Programming fundamentals
Last updated