Skip to the content

Lesson 37 of 296

Loops: for, while, break and continue

What you will learn

  • What a loop is and why we need loops
  • The for loop, part by part
  • while and do ... while
  • break and continue
  • Infinite loops and off-by-one errors
  • How to trace a loop by hand
On this page

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
5

A for loop has three parts inside the brackets, separated by semicolons:

PartCodeWhen it runsMeaning
Startlet i = 1Once, at the very beginningCreate a counter
Conditioni <= 5Before every iterationKeep going while this is true
Updatei++After every iterationChange 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);
IterationiCondition i <= 4total after the block
Start1-0
11true1
22true3
33true6
44true10
-5false, stop10

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, 20

Looping 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 cherry

Start 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);       4

do ... 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 item

Correct: 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

  • <= with length.
  • Forgetting to update the counter in a while loop.
  • Changing the counter inside the block by mistake.
  • Using break when you meant continue.
  • 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

WordMeaning
LoopCode that repeats
IterationOne run of the loop's block
CounterA variable that tracks which iteration it is, often i
breakStops the loop completely
continueSkips to the next iteration
Infinite loopA loop that never ends
Off-by-one errorLooping one time too many or too few

Now prove it

This lesson is complete when you pass the quiz and all three practice levels.