Exit loop early

2 snippets across 2 stacks — JavaScript, Python

JSJavaScript

break and continue

JS · Control Flow
syntax
break;     // exit loop
continue;  // skip to next iteration
example
const data = [3, -1, 7, 0, 5, -3, 9];
const positives = [];

for (const n of data) {
  if (n < 0) continue;  // skip negatives
  if (positives.length >= 3) break;  // stop after 3
  positives.push(n);
}
console.log(positives); // [3, 7, 5]

Note break exits the innermost loop. Use labeled breaks to exit outer loops: outer: for (...) { for (...) { break outer; } }

PYPython

break & continue

PY · Control Flow
syntax
break    # exit loop
continue # skip to next iteration
example
for n in range(1, 20):
    if n % 7 == 0:
        print(f"Found first multiple of 7: {n}")
        break
    if n % 2 == 0:
        continue
    print(f"Odd: {n}")
output
Odd: 1
Odd: 3
Odd: 5
Found first multiple of 7: 7

Note break exits only the innermost loop. To break out of nested loops, refactor into a function and use return.