The while loop has its three ingredients scattered around: the starting point before the loop, the condition at the top, and the update somewhere inside. That's easy to mess up. So JavaScript has another loop that puts all three ingredients together in one line. It's called the for loop, and it's the loop you'll use most often:
for (let i = 1; i <= 5; i++) {
console.log(`Lap number ${i}`);
}
It prints
Lap number 1 Lap number 2 Lap number 3 Lap number 4 Lap number 5
The part inside the parentheses has three pieces separated by semicolons:
for (start; condition; update) {
// body: the code to repeat
}
| Piece | In our example | When it runs |
|---|---|---|
| Start | let i = 1 | Once, before the loop begins |
| Condition | i <= 5 | Before every iteration. If false, the loop stops |
| Update | i++ | After every iteration |
The variable i is called the loop counter. Why i? It's short for "index" (or "iteration"), and it's a tradition going back decades. For loops inside loops, programmers use j, and then k. You can name it anything, but i is what everyone expects.
Counting in different ways
You can count from anywhere, to anywhere, by any step:
// Count down
for (let i = 3; i >= 1; i--) {
console.log(i);
}
// Count by twos
for (let i = 0; i <= 10; i += 2) {
console.log(`Even: ${i}`);
}
It prints
3 2 1 Even: 0 Even: 2 Even: 4 Even: 6 Even: 8 Even: 10
The times table
Here's a classic use for a loop: printing a multiplication table.
const number = 7;
for (let i = 1; i <= 10; i++) {
console.log(`${number} x ${i} = ${number * i}`);
}
It prints
7 x 1 = 7 7 x 2 = 14 7 x 3 = 21 7 x 4 = 28 7 x 5 = 35 7 x 6 = 42 7 x 7 = 49 7 x 8 = 56 7 x 9 = 63 7 x 10 = 70
Change number to any value, and you instantly get its whole times table. Your primary school maths teacher would have loved this.
The accumulator pattern
A super common trick is to use a loop to build up a total. You start with a variable at zero (the accumulator), and add to it on each iteration:
let sum = 0;
for (let i = 1; i <= 100; i++) {
sum += i;
}
console.log(`1 + 2 + 3 + ... + 100 = ${sum}`);
It prints
1 + 2 + 3 + ... + 100 = 5050
Legend has it that in the late 1700s, a teacher told his class to add up all the numbers from 1 to 100, hoping it would keep them busy for a while. A young boy named Carl Friedrich Gauss handed in the answer almost immediately: 5050. He'd noticed that 1 + 100 = 101, 2 + 99 = 101, 3 + 98 = 101, and so on. There are 50 of those pairs, so the total is 50 × 101 = 5050. Gauss went on to become one of the greatest mathematicians in history. Your loop gets the same answer, just with less genius and more electricity.
while or for?
Use for when... | Use while when... |
|---|---|
| You know how many times to loop | You don't know how many times you'll need to loop |
| You're counting from one number to another | You're waiting for something to happen |
| "Do this 10 times" | "Keep going until the user guesses correctly" |
Here's a perfect while example. You save $75 every week. How many weeks until you've saved $1,000 for a new phone? We don't know in advance, so we keep going while we haven't reached the goal:
const goal = 1000;
const weeklySavings = 75;
let savings = 0;
let weeks = 0;
while (savings < goal) {
savings += weeklySavings;
weeks++;
}
console.log(`It will take ${weeks} weeks to save $${goal}.`);
console.log(`You'll have $${savings} ($${savings - goal} spare for a phone case!)`);
It prints
It will take 14 weeks to save $1000. You'll have $1050 ($50 spare for a phone case!)