break and continue both change the normal flow of a loop, but they mean different things.
break: end the current loop immediately.continue: skip the rest of the current iteration and start the next one.
break
Use break when the loop has already achieved its goal, or when continuing the loop no longer makes sense.
The program below checks whether an integer is prime. As soon as it finds one divisor of n, it knows n is not prime, so it can stop checking.
let n = 17;
let prime = n > 1;
for (let i = 2; i <= Math.sqrt(n); i++) {
if (n % i === 0) {
prime = false;
break;
}
}
console.log(prime ? "Prime" : "Not prime");One possible run:
Enter an integer: 17
17 is a prime numberThere is no need to check all the way to n - 1. If a number has a factor larger than its square root, it must also have a paired factor smaller than its square root, so checking through sqrt(n) is enough.
KNOWLEDGE QUIZ
continue
continue does not end the whole loop. It skips the remaining code in the current iteration and moves directly to the next iteration.
The program below reads 10 integers and computes the sum of squares of non-negative integers. When it sees a negative number, it skips that iteration.
let sumSquare = 0;
for (let i = 0; i < 10; i++) {
let num = Number(prompt("Enter an integer:"));
if (num < 0) {
continue;
}
sumSquare += num * num;
}One possible run:
Enter 10 integers:
5
7
-2
0
4
-4
-9
3
9
5
Sum of squares of non-negative integers: 205When num < 0, continue skips sum_square += num * num, so negative numbers do not contribute to the result. Note that 0 is not negative; its square is 0, so adding it does not change the total.
KNOWLEDGE QUIZ
Choosing between them
Use break when you want the whole loop to stop. Use continue when you only want to skip the rest of the current iteration and let the next iteration begin normally.
for (let x = 1; x <= 5; x++) {
if (x === 3) {
continue;
}
console.log(x);
}Output:
1
2
4
5The value 3 is skipped, but the loop does not end.
KNOWLEDGE QUIZ
Comparison experiment
After reading what break and continue mean, use the component below to compare them step by step. When the loop reaches x === 3, continue only skips the current iteration, while break ends the whole loop early.
Parcel sorter: skip or shut down?
The scanner meets a damaged parcel at x = 3. Compare continue (send it aside) with break (stop the belt).
Belt waitingSkip negatives and stop when a value is too large
Read a count n, then read integers one by one: skip negatives, stop above 100, and accumulate the remaining values.
- Read n for the maximum number of inputs.
- Use a for loop and continue to skip negative values.
- Use break above 100, then print the sum and count.