JavaScript Break and Continue
The break and continue statements give you fine-grained control inside loops by stopping them early or skipping individual iterations.
Changing the flow of a loop
Sometimes a loop should not run to its natural end. You might find the item you were searching for and want to stop, or you might want to ignore certain values and move straight to the next pass. JavaScript provides two keywords for exactly this: break exits the loop completely, while continue skips the rest of the current iteration and jumps to the next one.
Using break to stop early
<!DOCTYPE html>
<html>
<body>
<h2>Using break to stop early</h2>
<script>
const numbers = [4, 8, 15, 16, 23, 42];
for (let i = 0; i < numbers.length; i++) {
if (numbers[i] === 16) {
console.log("Found 16 at index", i);
break; // stop looping immediately
}
}
// Found 16 at index 3
</script>
</body>
</html>Once break runs, the loop ends and execution continues with the code after it. This is efficient for searches because there is no reason to keep checking the remaining elements after you have found what you need.
Using continue to skip values
<!DOCTYPE html>
<html>
<body>
<h2>Using continue to skip values</h2>
<script>
for (let i = 1; i <= 6; i++) {
if (i % 2 === 0) {
continue; // skip even numbers
}
console.log(i);
}
// 1
// 3
// 5
</script>
</body>
</html>- break terminates the entire loop right away.
- continue abandons the current iteration but keeps the loop running.
- Both work in for, while, and do...while loops.
- In nested loops, they affect only the innermost loop unless you use a label.
break vs. continue at a glance
Exercise: JavaScript Loops
How many times does a do...while loop run if its condition is false from the start?