3.10 break and continue
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 = Number(prompt("Enter an integer:"));
let isPrime = n > 1;
for (let i = 2; i <= Math.sqrt(n); i++) {
if (n % i === 0) {
isPrime = false;
break;
}
}
if (isPrime) {
console.log(`${n} is a prime number`);
} else {
console.log(`${n} is not a prime number`);
}There 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 Math.sqrt(n) is enough.
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 computes the sum of squares of non-negative integers. When it sees a negative number, it skips that iteration.
const nums = [5, 7, -2, 0, 4, -4, -9, 3, 9, 5];
let sumSquare = 0;
for (const num of nums) {
if (num < 0) {
continue;
}
sumSquare += num * num;
}
console.log("Sum of squares:", sumSquare);Output:
Sum of squares: 205When num < 0, continue skips sumSquare += num * num, so negative numbers do not contribute to the result.
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.