Loops: while and for
A loop repeats a block of code, and the two main forms differ in whether you know how many times you need to repeat.
while repeats until a condition turns false. for gathers the start, the test and the step onto one line, which suits counting. for-of walks a list directly, and break and continue steer any of them.
EXERCISE
1while: Repeat Until Something Changes
A while loop checks a condition, runs its block, and goes back to check again, which suits work of unknown length.
while is the simplest loop. It is an if that goes back round.
The shape, and a first run:
let count = 1;
while (count <= 3) {
console.log(count);
count = count + 1; // without this, it never stops
}
// 1
// 2
// 3
Three things must line up, and all three are your job:
let n = 0; // 1. a starting point
while (n < 5) { // 2. a condition that will eventually be false
console.log(n);
n++; // 3. something that moves toward that
}
// Forget the third and you have an infinite loop:
// let m = 0;
// while (m < 5) { console.log(m); }
// This prints 0 forever and freezes the tab.
Where while genuinely fits: when you cannot count in advance:
let balance = 100;
let months = 0;
while (balance > 0) {
balance = balance - 30;
months++;
}
console.log(`Ran out after ${months} months`); // Ran out after 4 months
// Nobody worked out "4" beforehand. The loop discovered it.
Pro Tip: Every
whileloop is a promise that the condition will become false. When you write one, find the line that moves it towards false before you run the code, because an infinite loop in a browser tab locks the page and you lose whatever was in it. If there is no such line, you wanted a different shape.
EXERCISE
2for: Counting, with Everything on One Line
A for loop gathers the three parts of a counted repeat into one header, which is why it is the standard way to count.
The for header holds the same three parts a while needs, side by side.
The same loop, both ways:
// while: the three parts are scattered
let i = 0;
while (i < 3) {
console.log(i);
i++;
}
// for: the three parts are together
for (let i = 0; i < 3; i++) {
console.log(i);
}
// 0
// 1
// 2
Reading the header:
for (let i = 0; i < 3; i++) { }
// ^start^ ^test^ ^step^
//
// 1. let i = 0 runs once, before anything
// 2. i < 3 checked before every turn; false means stop
// 3. i++ runs after every turn
Walking an array by index:
const names = ["Ada", "Grace", "Alan"];
for (let i = 0; i < names.length; i++) {
console.log(`${i}: ${names[i]}`);
}
// 0: Ada
// 1: Grace
// 2: Alan
// Counting backwards is just a different header:
for (let i = names.length - 1; i >= 0; i--) {
console.log(names[i]);
}
// Alan
// Grace
// Ada
Use let, not var, for the counter:
for (let i = 0; i < 3; i++) { }
console.log(i); // ReferenceError: i is not defined <- good, it is finished
for (var j = 0; j < 3; j++) { }
console.log(j); // 3 <- var leaked out of the loop
i < names.length rather than i <= names.length is the boundary that trips everyone at least once. An array of three items has indexes 0, 1 and 2, so the last valid index is always length - 1. Using <= reads index 3, which is undefined, and the bug surfaces as an unexplained blank at the end of a list.
EXERCISE
3for-of, break and continue
When you want every item in a list and do not care about the index, there is a loop that says exactly that.
for-of hands you the items, not the positions:
const names = ["Ada", "Grace", "Alan"];
for (const name of names) {
console.log(name);
}
// Ada
// Grace
// Alan
// No counter, no length, no names[i]. Nothing to get wrong.
const works here because each turn of the loop creates a fresh name.
It works on strings too:
for (const letter of "cat") {
console.log(letter);
}
// c
// a
// t
break leaves the loop entirely:
const numbers = [3, 7, 12, 5, 9];
for (const n of numbers) {
if (n > 10) {
console.log(`Found ${n}`);
break; // stop looking, we are done
}
}
// Found 12
// 5 and 9 were never examined.
continue skips the rest of this turn only:
for (const n of numbers) {
if (n % 2 === 0) continue; // skip even numbers
console.log(n);
}
// 3
// 7
// 5
// 9
Choosing between the three:
// Need the index, or a non-standard step? Use for.
for (let i = 0; i < names.length; i += 2) { }
// Need every item, in order? Use for-of.
for (const name of names) { }
// Repeating until a condition changes? Use while.
// while (balance > 0) { }
Pro Tip: Prefer
for-ofwhenever you simply want each item, because it removes the counter, the length check and the index lookup, which is where the bugs in a counted loop actually live. Keep the classicforfor when the index itself is part of the job.
