Loops
A loop repeats code so you don't have to write it many times. Loops print every item in a list, add up a column of prices, retry a step until it succeeds, and much more. JavaScript has several kinds, each suited to a different job.
The for loop
The classic for loop is ideal when you know how many times to repeat. Its brackets hold three parts separated by semicolons: a start (usually creating a counter), a condition checked before every round, and an update run after every round.
for (let i = 1; i <= 5; i++) {
console.log(`3 x ${i} = ${3 * i}`);
}
Step by step: i starts at 1; the condition i <= 5 is true, so the body runs; then i++ makes i 2, and the condition is checked again. When i reaches 6 the condition is false and the loop ends.
Loops often count through array indexes: for (let i = 0; i < arr.length; i++). Note the <: the last index is length - 1.
while and do...while
Use while when you don't know in advance how many rounds you need, only the condition for stopping:
let savings = 0;
let weeks = 0;
while (savings < 1000) {
savings += 300;
weeks++;
}
console.log(`Reached KES ${savings} after ${weeks} weeks`);
After 3 weeks the savings are 900, still below 1000, so the loop runs a fourth time and reaches 1200. A do...while loop checks its condition at the end, so its body always runs at least once, handy for "ask, then check" situations:
let attempts = 0;
do {
attempts++;
console.log("Attempt", attempts);
} while (attempts < 3);
If the condition never becomes false you get an infinite loop and the browser tab freezes. Make sure something inside the loop moves towards the end, for example weeks++ or savings += 300. If a tab hangs, close it and check your condition.
for...of: loop over values
for...of walks through the values of anything iterable, such as an array or a string, without any counter. It is the cleanest choice for most array loops.
const towns = ["Nakuru", "Eldoret", "Thika"];
for (const town of towns) {
console.log(town.toUpperCase());
}
for (const letter of "Hi!") {
console.log(letter);
}
Using const here is fine: each round gets a fresh town variable.
for...in: loop over object keys
for...in goes through the property names (keys) of an object:
const prices = { tea: 30, mandazi: 10, chapati: 20 };
for (const item in prices) {
console.log(item, "costs", prices[item]);
}
Don't use for...in on arrays. It gives you the indexes as strings ("0", "1"…) and can include extra properties. Remember: of for values of arrays and strings, in for keys of objects.
break and continue
break leaves a loop immediately; continue skips the rest of the current round and moves to the next.
for (let n = 1; n <= 10; n++) {
if (n % 2 === 0) continue; // skip even numbers
if (n > 7) break; // stop completely after 7
console.log(n);
}
Even numbers are skipped by continue. When n is 9, the break ends the loop before 9 is printed. For arrays you will often use methods like forEach, map and filter instead of writing loops by hand; see Array Methods.
Key points
for (start; condition; update)repeats a known number of times.whilerepeats while a condition holds;do...whilealways runs at least once.for...ofloops over values (arrays, strings);for...inloops over object keys.breakexits a loop andcontinueskips to the next round.- Make sure every loop can end, and watch for off-by-one errors with
<vs<=.
Tip: use the ← and → keys to move between pages.
