Apply JavaScript loops (for, while, do-while)
21 Programming for the web: JavaScript Loops
🔁 The “for” Loop – A Countdown Race
Think of a for loop like a countdown race. You set a starting point, a finish line, and a step you take each time. The loop keeps going until you reach the finish line.
- Initialize a counter:
let i = 0; - Set a condition:
i < 10;– keep going whileiis less than 10. - Increment:
i++;– add 1 toieach time. - Execute the code block inside the braces.
Example: Print numbers 0–9 to the console.
for (let i = 0; i < 10; i++) {
console.log(i);
}
🔄 The “while” Loop – A Waiting Game
Imagine you’re waiting for a bus. You keep checking the clock until the bus arrives. That’s a while loop: it keeps running as long as a condition is true.
- Set up a condition:
let count = 0; - Check the condition:
while (count < 5) - Execute the block and update the counter inside the loop.
Example: Count to 5 and stop.
let count = 0;
while (count < 5) {
console.log(count);
count++;
}
🌀 The “do‑while” Loop – A Promise Keeper
A do‑while loop is like a promise: you promise to do something at least once, then keep doing it while the condition is true.
- Execute the block first.
- Check the condition at the end.
- Repeat if the condition remains true.
Example: Ask a user for a password until they enter the correct one.
let password = "";
do {
password = prompt("Enter password:");
} while (password !== "openSesame");
📊 Loop Syntax Comparison
| Loop Type | Syntax | When to Use |
|---|---|---|
| for |
for (init; condition; increment) { … }
|
Known number of iterations. |
| while |
while (condition) { … }
|
Unknown iterations, check before each run. |
| do‑while |
do { … } while (condition);
|
Must run at least once, check after each run. |
🧩 Choosing the Right Loop
- for – When you know how many times you’ll loop (e.g., iterate over an array).
- while – When the loop depends on a condition that could be false before the first run.
- do‑while – When you need to run the loop body at least once (e.g., form validation).
💡 Quick Quiz
1️⃣ Which loop guarantees at least one execution?
2️⃣ Write a for loop that prints the even numbers from 2 to 20.
3️⃣ When would you prefer a while loop over a for loop?
Revision
Log in to practice.