Loops: for, while and repeating work
Repeat tasks with for, while and do...while loops, control them with break and continue, and build totals with accumulators.
In this lesson you will
- Write for and while loops
- Build totals with an accumulator
- Control loops with break and continue
- Avoid infinite loops
About 16 minutes
Let the computer do the boring part
Suppose a teacher asks you to write “I will not talk in class” one hundred times. You could write it by hand, or you could say: “repeat this 100 times”. That second sentence is a loop. Computers never get bored or tired, so repeating work is what they do best. Loops let you handle a list of 10 or 10,000 items with the same few lines.
The for loop
for (let i = 1; i <= 5; i++) {
console.log("Round " + i);
}
A for loop has three parts inside the brackets, separated by semicolons:
- Start:
let i = 1runs once, before the loop begins. It creates a counter. - Condition:
i <= 5is checked before every round. If it is true, the loop body runs. If false, the loop ends. - Step:
i++runs after each round, adding one to the counter. - Then the cycle repeats from the condition until it is false.
Print the numbers 1 to 10, each on its own line. Then change it to print only to 5.
// write a for loop
for (let i = 1; i <= 10; i++) { console.log(i); }
for (let i = 1; i <= 10; i++) {
console.log(i);
}
Counting patterns
// count down
for (let i = 5; i >= 1; i--) { console.log(i); }
// step by 2
for (let i = 0; i <= 10; i += 2) { console.log(i); }
// a multiplication table
for (let i = 1; i <= 5; i++) {
console.log(`7 x ${i} = ${7 * i}`);
}
Adding things up
Loops often build a result piece by piece. This pattern, called an accumulator, is everywhere in programming: start with an empty total, and add to it each time round.
let sum = 0;
for (let i = 1; i <= 100; i++) {
sum += i;
}
console.log(sum); // 5050
The while loop
Use while when you do not know in advance how many rounds you need. It keeps going as long as its condition is true.
let money = 100;
let days = 0;
while (money > 0) {
money -= 30;
days++;
}
console.log(`Money lasted ${days} days`); // 4
An infinite loop: the condition never becomes false, because you forgot to change the variable. while (true) { } will freeze a tab. Always ask: what makes this loop stop?
do…while
let tries = 0;
do {
tries++;
console.log("Attempt " + tries);
} while (tries < 3);
A do...while loop checks its condition after the body, so the body always runs at least once. It is handy for “ask, then check” situations.
break and continue
for (let i = 1; i <= 10; i++) {
if (i === 3) continue; // skip this round
if (i === 6) break; // leave the loop
console.log(i); // 1 2 4 5
}
breakends the whole loop immediately.continueskips the rest of this round and jumps to the next one.
Print only the even numbers from 1 to 20 using a for loop and the remainder operator. Stop early with break if you reach 14.
for (let i = 1; i <= 20; i++) {
// print only evens, break at 14
}
if (i % 2 !== 0) continue; and if (i > 14) break;
for (let i = 1; i <= 20; i++) {
if (i % 2 !== 0) continue;
if (i > 14) break;
console.log(i);
}
Loops inside loops
for (let row = 1; row <= 3; row++) {
let line = "";
for (let col = 1; col <= 4; col++) {
line += "* ";
}
console.log(line);
}
The inner loop runs completely for every round of the outer loop: 3 rows times 4 columns gives 12 stars. Nested loops are how programs handle tables, grids and games.
A real example: FizzBuzz
This is a famous warm-up exercise used in interviews. For numbers 1 to 15: print Fizz if divisible by 3, Buzz if divisible by 5, FizzBuzz if both, otherwise the number.
for (let i = 1; i <= 15; i++) {
if (i % 15 === 0) console.log("FizzBuzz");
else if (i % 3 === 0) console.log("Fizz");
else if (i % 5 === 0) console.log("Buzz");
else console.log(i);
}
Use for when you know how many times, while when you repeat until something changes. In the next lessons you will meet for...of, the friendliest way to loop through lists.
Worked example: a savings plan
You save 500 each month and your savings grow by 1 percent every month. How long until you reach 10,000? You do not know the number of months in advance, so this is a job for while.
let balance = 0;
let months = 0;
while (balance < 10000) {
balance += 500;
balance += balance * 0.01;
months++;
}
console.log(`${months} months, balance ${balance.toFixed(2)}`);
The condition asks a question each round: are we there yet? The body moves us closer. The counter months records how many rounds it took. This pattern of “repeat until the goal, and count the steps” appears in games, finance and animation.
Looping through text
Strings can be looped too, because they are sequences of characters. This is how you count letters, find vowels or check a password for digits.
const word = "banana";
let count = 0;
for (const letter of word) {
if (letter === "a") count++;
}
console.log(`There are ${count} letter a in ${word}`); // 3
Count the vowels (a, e, i, o, u) in the sentence and print the total. Hint: the includes method on a string of vowels helps.
const sentence = "Learning JavaScript is fun";
let vowels = 0;
// loop and count
console.log(vowels);
for (const ch of sentence.toLowerCase()) { if (“aeiou”.includes(ch)) vowels++; }
const sentence = "Learning JavaScript is fun";
let vowels = 0;
for (const ch of sentence.toLowerCase()) {
if ("aeiou".includes(ch)) vowels++;
}
console.log(vowels);
Practice ideas
- Print a countdown from 10 to 1 and then “Liftoff!”.
- Sum only the odd numbers from 1 to 99.
- Print the 12 times table with a nested loop.
- Find the first number above 100 that is divisible by both 7 and 9.
Check what you learned
Five quick questions. Pick an answer and you will see straight away whether it is right and why.
What are the three parts of a for loop in the brackets?
- Start, condition, step
- If, else, then
- Input, output, loop
- Name, value, type
Initialisation, condition and increment.
What does for (let i = 0; i < 3; i++) print if it logs i?
- 0 1 2
- 1 2 3
- 0 1 2 3
- 3 2 1
i starts at 0 and the loop stops before reaching 3.
When should you use while instead of for?
- Never
- When you don’t know how many rounds are needed
- Only for arrays
- For strings only
while repeats until a condition changes.
What does continue do?
- Ends the loop
- Skips to the next round
- Restarts the program
- Pauses
continue jumps to the next iteration.
What causes an infinite loop?
- A condition that never becomes false
- Using let
- Using console.log
- Indentation
Nothing changes the condition, so it never ends.
Summary
- A for loop has start, condition and step.
- while repeats until a condition becomes false.
- break leaves, continue skips.
- Always make sure something ends the loop.
Questions
Which loop is fastest?
For everyday code the difference is tiny. Choose the one that reads best.
Why do loops start at 0 so often?
Positions in lists start at 0, so loops that walk through lists usually start there too.
How do I stop a frozen page from an infinite loop?
Close the tab or stop the script from the browser. Then fix the condition.
