Continue
While break exits the loop entirely, the continue keyword is less destructive: it immediately stops the current iteration and jumps straight to the next evaluation step of the loop.
Using Continue
This is highly useful for skipping over specific elements that do not meet your criteria, without halting the entire process.
for (let i = 0; i < 10; i++) {
// If the number is even, skip to the next iteration
if (i % 2 === 0) {
continue;
}
// This line is only reached by odd numbers
console.log(i);
}
// Output: 1, 3, 5, 7, 9
Practical Example
Finding prime numbers is a great algorithmic exercise to demonstrate break and continue.
function printPrimes(max) {
for (let n = 2; n <= max; n++) {
if (n === 2) {
console.log(n);
continue; // Found it, move to the next number
}
if (n % 2 === 0) {
continue; // Skip all even numbers
}
let isPrime = true;
for (let i = 3; i * i <= n; i += 2) {
if (n % i === 0) {
isPrime = false;
break; // Not prime, stop checking inner loop
}
}
if (isPrime) {
console.log(n);
}
}
}
printPrimes(10);
// Output: 2, 3, 5, 7