Course progress0%
Course content

Module 1

Module 2

Module 3

Module 4

Module 5

Module 6

Module 7

Module 8

Module 9

Module 10

Module 11

Module 12

Module 13

Module 14

Module 15

Module 16

Module 17

Module 18

30 min

Loop Control and Small Statistics

Use break and continue deliberately

By the end of this lesson

  • Use break and continue deliberately
  • Distinguish skipping work from ending repetition

Clarify what should be skipped

A daily report numbers working slots 1 through 6. Slot 3 is cancelled. We want to count all other slots. Does cancelling slot 3 mean later slots are cancelled too?

let countedSlots = 0;
for (let slot = 1; slot <= 6; slot++) {
  if (slot === 3) {
    continue;
  }
  countedSlots++;
}
console.assert(countedSlots === 5);

continue skips the rest of the current iteration. In this for loop the update still runs. break exits the nearest enclosing loop immediately. Replacing continue with break would count only slots 1 and 2, which implements a different policy.

Guided search

let firstMatch = null;
for (let candidate = 1; candidate <= 20; candidate++) {
  if (candidate % 7 === 0) {
    firstMatch = candidate;
    break;
  }
}
console.assert(firstMatch === 7);

The remainder operator % helps check divisibility here. Once the first qualifying value is found, further candidates cannot change the answer we want. Null means no result was found under this convention.

Independent exercise

Sum the even numbers from 1 through 10 and calculate their average. Use a sum and a count; predict both before execution. Explain what must happen if the selected range contains no even numbers.

Correction

let sum = 0;
let count = 0;
for (let value = 1; value <= 10; value++) {
  if (value % 2 !== 0) continue;
  sum += value;
  count++;
}
let average = null;
if (count > 0) average = sum / count;
console.assert(sum === 30);
console.assert(average === 6);

+= adds to the current value. The guard avoids dividing by zero when no values qualify. Later we will repeat this reasoning over actual collections and search for their minimum and maximum.

Review

Use loop control to clarify intent, not to patch a confused loop. A direct condition around a small body can be clearer than several continue statements. Choose the version you can explain step by step.

Lesson complete?

Your progress is saved on this device.