Skip iteration

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.

Frequently asked questions

How do you skip iteration?
This task is covered in 2 stacks on this page: JavaScript, Python. The "break and continue" snippet in JavaScript uses `break; // exit loop`.
Which code does the JavaScript example use?
The "break and continue" snippet uses `break; // exit loop`, from the Control Flow section of the JavaScript cheat sheet.
Which stacks cover "skip iteration" on this page?
JavaScript, Python. Together they hold 2 copy-ready snippets for this task.
Is there anything to watch out for?
Yes. For "break and continue": break exits the innermost loop. Use labeled breaks to exit outer loops: outer: for (...) { for (...) { break outer; } }