JavaScript skipping iterations


In JavaScript, skipping iterations within a loop means bypassing certain parts of the loop’s body based on a condition. This allows you to control the flow of execution and avoid executing specific code for some iterations. The primary way to skip iterations is using the continue statement.

continue Statement

The continue statement is used to skip the rest of the code inside the current loop iteration and proceed with the next iteration of the loop. It works with for, while, and do...while loops.

Syntax

continue;

How It Works

  1. Condition Check: The loop checks the condition for the next iteration.
  2. Skip Execution: If continue is encountered, the remaining code inside the loop for the current iteration is skipped.
  3. Next Iteration: The loop proceeds with the next iteration.

Example

Here’s an example of using continue in a for loop to skip even numbers:

for (let i = 0; i < 10; i++) { if (i % 2 === 0) { continue; // Skips the rest of the loop body for even numbers } console.log(i); // Logs only odd numbers: 1, 3, 5, 7, 9 }
  • Explanation:
    • The condition if (i % 2 === 0) checks if i is an even number.
    • If i is even, the continue statement is executed, skipping the console.log(i) statement.
    • Odd numbers are logged because the continue statement is not triggered for them.

Skipping Iterations in Other Loops

while Loop Example

Using continue in a while loop:

let count = 0; while (count < 10) { count++; if (count % 2 === 0) { continue; // Skips printing for even numbers } console.log(count); // Logs: 1, 3, 5, 7, 9 }
  • Explanation:
    • The loop increments count and checks if it is even.
    • If even, continue is executed, skipping the console.log(count) statement.
    • Only odd values are printed.

do...while Loop Example

Using continue in a do...while loop:

let index = 0; do { index++; if (index % 2 === 0) { continue; // Skips printing for even numbers } console.log(index); // Logs: 1, 3, 5, 7, 9 } while (index < 10);
  • Explanation:
    • Similar to the previous examples, continue skips the console.log(index) statement for even values.

Summary

  • continue Statement: Skips the remainder of the code in the current iteration of the loop and proceeds with the next iteration.
  • Usage: Useful when you need to avoid executing specific parts of the loop body based on a condition.
  • Loops: Can be used with for, while, and do...while loops.