Lesson 37 of 296
Loops: for, while, break and continue
What you will learn
- What a loop is and why we need loops
- The
forloop, part by part whileanddo ... whilebreakandcontinue- Infinite loops and off-by-one errors
- How to trace a loop by hand
On this page
- What is a loop?
- The for loop
- Tracing a loop by hand
- Counting in other ways
- Looping over an array by index
- The while loop
- do ... while
- break: stop the loop
- continue: skip to the next iteration
- Infinite loops
- Off-by-one errors
- Loops inside loops
- Classic interview warm-up: FizzBuzz
- Common mistakes
- How to say it in an interview
- Key words
What is a loop?
A loop repeats a block of code many times. Without loops, printing the numbers 1 to 100 would need 100 lines. With a loop, it needs 3.
Each time the loop runs its block is called an iteration.
The for loop
for (let i = 1; i <= 5; i++) {
console.log(i);
}Shows:
1
2
3
4
5A for loop has three parts inside the brackets, separated by semicolons:
| Part | Code | When it runs | Meaning |
|---|---|---|---|
| Start | let i = 1 | Once, at the very beginning | Create a counter |
| Condition | i <= 5 | Before every iteration | Keep going while this is true |
| Update | i++ | After every iteration | Change the counter |
i is the usual name for a loop counter ("index").
Tracing a loop by hand
Being able to trace a loop on paper is essential in interviews.
let total = 0;
for (let i = 1; i <= 4; i++) {
total = total + i;
}
console.log(total);| Iteration | i | Condition i <= 4 | total after the block |
|---|---|---|---|
| Start | 1 | - | 0 |
| 1 | 1 | true | 1 |
| 2 | 2 | true | 3 |
| 3 | 3 | true | 6 |
| 4 | 4 | true | 10 |
| - | 5 | false, stop | 10 |
Result: 10.
Counting in other ways
for (let i = 10; i >= 1; i--) { ... } 10 down to 1
for (let i = 0; i <= 20; i += 5) { ... } 0, 5, 10, 15, 20Looping over an array by index
const fruits = ["apple", "banana", "cherry"];
for (let i = 0; i < fruits.length; i++) {
console.log(i, fruits[i]);
}Shows:
0 apple
1 banana
2 cherryStart at 0 and use < (not <=) with length, because the last index is length - 1. Lesson 42 shows simpler ways to loop over arrays.
The while loop
while repeats as long as a condition is true. Use it when you do not know in advance how many times to loop.
let balance = 100;
let months = 0;
while (balance > 0) {
balance = balance - 30;
months++;
}
console.log(months); 4do ... while
Like while, but checks the condition after the block, so the block always runs at least once.
let input;
do {
input = askUser();
} while (input === "");It is rare in everyday code.
break: stop the loop
const numbers = [4, 9, 15, 2, 20];
for (let i = 0; i < numbers.length; i++) {
if (numbers[i] > 10) {
console.log("First number over 10:", numbers[i]);
break;
}
}Shows First number over 10: 15 and stops. It does not check 2 or 20.
continue: skip to the next iteration
for (let i = 1; i <= 6; i++) {
if (i % 2 === 0) {
continue;
}
console.log(i);
}Shows 1, 3, 5. When i is even, continue skips the rest of the block and goes to the next number.
Infinite loops
If the condition never becomes false, the loop never stops. The browser tab freezes.
let i = 0;
while (i < 5) {
console.log(i);
// forgot i++
}Always check that something inside the loop moves it towards the end.
Off-by-one errors
Looping one time too many or one time too few is the most common loop bug.
for (let i = 0; i <= fruits.length; i++) one too many: the last fruits[i] is undefined
for (let i = 1; i < fruits.length; i++) one too few: skips the first itemCorrect: for (let i = 0; i < fruits.length; i++).
Loops inside loops
for (let row = 1; row <= 3; row++) {
for (let col = 1; col <= 3; col++) {
console.log(row, col);
}
}The inner loop runs completely for each turn of the outer loop: 3 x 3 = 9 lines. Nested loops are slow with big data. Part 10 explains why with Big-O.
Classic interview warm-up: FizzBuzz
Print numbers 1 to 15. For multiples of 3 print "Fizz", multiples of 5 print "Buzz", multiples of both print "FizzBuzz".
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);
}
}The % 15 check must come first. Otherwise 15 would print "Fizz" and stop (Lesson 36: the first true condition wins).
Common mistakes
<=withlength.- Forgetting to update the counter in a
whileloop. - Changing the counter inside the block by mistake.
- Using
breakwhen you meantcontinue. - The FizzBuzz order mistake.
How to say it in an interview
"A for loop has an initialiser, a condition checked before each iteration, and an update run after each one. I use while when the number of iterations is unknown. break exits the loop, continue skips to the next iteration. The common pitfalls are off-by-one errors, so with arrays I start at zero and use less-than length, and infinite loops when the condition never changes."
Key words
| Word | Meaning |
|---|---|
| Loop | Code that repeats |
| Iteration | One run of the loop's block |
| Counter | A variable that tracks which iteration it is, often i |
| break | Stops the loop completely |
| continue | Skips to the next iteration |
| Infinite loop | A loop that never ends |
| Off-by-one error | Looping one time too many or too few |
Now prove it
This lesson is complete when you pass the quiz and all three practice levels.