JS Break
break exits a loop or switch; continue skips to the next iteration. Both can target labels for nested loops.
Examples
JS
// break — find the first negative
for (const n of nums) {
if (n < 0) {
console.log("first negative:", n);
break;
}
}
// continue — skip evens
for (const n of nums) {
if (n % 2 === 0) continue;
console.log("odd:", n);
}
Labeled break (rare but useful)
JS
outer:
for (const row of grid) {
for (const cell of row) {
if (cell === target) {
console.log("found");
break outer; // exits BOTH loops
}
}
}
break vs return
break | return | |
|---|---|---|
| Exits | Current loop / switch | The entire function |
| Returns a value? | No | Yes |
| Works in array methods? | ❌ (use a regular loop) | From the callback only — not the array method |
Tip: Need to "break out" of
forEach? You can't. Switch to for…of and use break, or use some / find which stop as soon as the callback returns true.Example
Example
<!DOCTYPE html>
<html>
<body>
<p id="out"></p>
<script>
document.getElementById("out").textContent = "Hello from JS Break!";
</script>
</body>
</html>
Try it Yourself »
Exercise
Skip negatives but keep going.
for (const n of nums) { if (n < 0)
; console.log(n); }
Eight letters.
Discussion
Loading…