[JavaScript] Skipping Specific Loop Iterations with the ‘continue’ Statement

目次

Overview

In looping processes like for or while, you use the continue statement when you want to skip the current iteration for a specific condition and proceed to the next cycle. This prevents deep “nesting” of if statements and makes your code easier to read. This article explains how continue works using a basic example that filters out even numbers and outputs only odd numbers.

Specifications (Input/Output)

  • Input: A numerical counter from 0 to 9.
  • Output:
    • Skip logging if the condition (even number) is met.
    • Output the number to the console only if the condition is not met (odd number).

Basic Usage

Write continue; at any point inside the loop block. When this line is executed, all remaining code in the block is ignored, and the loop returns to the start (evaluating the condition or executing the increment expression).

Full Code (HTML / JavaScript)

HTML (index.html)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>continue Statement Demo</title>
    <script src="continue-demo.js" defer></script>
</head>
<body>
    <div class="container">
        <h1>Please check the Console</h1>
        <p>Only odd numbers are filtered and displayed.</p>
    </div>
</body>
</html>

JavaScript (continue-demo.js)

This structure compares a standard nested if style with a cleaner approach using continue.

/**
 * Function to skip even numbers and process only odd numbers.
 * Uses 'continue' as a guard clause.
 */
const printOddNumbers = () => {
    console.log("--- Starting loop process ---");

    for (let i = 0; i < 10; i++) {
        // Condition: If i is an even number (divisible by 2)
        if (i % 2 === 0) {
            // When 'continue' is executed, the following console.log is skipped,
            // and the loop immediately moves to the next iteration (i++).
            continue;
        }

        // This line is only reached if the number is NOT even (i.e., odd)
        console.log(`Odd number found: ${i}`);
    }

    console.log("--- Loop ended ---");
};

// Execute
printOddNumbers();

Customization Points

  • Changing the skip condition: Change i % 2 === 0 to i % 3 === 0 to “skip multiples of 3.”
  • Excluding specific values: In list processing, you can use if (item === null) continue; to skip invalid data and continue the process.

Important Points

  • Difference from ‘break’: While break stops and “exits” the entire loop, continue only “skips the current cycle” and continues with the next one. Do not confuse the two.
  • Usage in while loops: When using continue inside a while loop, you must be careful. If you continue before the variable update (like i++), the variable will never change, leading to an “infinite loop.” Always pay attention to where you place the statement.

Advanced Usage

Reducing Nesting (Guard Clauses)

By using continue, you can keep the hierarchy of your code shallow even when dealing with complex conditions.

// [Bad Example] Deeply nested if statements
/*
for (let i = 0; i < 10; i++) {
    if (isSystemActive) {
        if (i % 2 !== 0) {
            console.log(i);
        }
    }
}
*/

// [Good Example] Using 'continue' to filter out mismatches early
const processWithGuard = (isSystemActive) => {
    for (let i = 0; i < 10; i++) {
        // Skip if the system is inactive
        if (!isSystemActive) continue;
        
        // Skip if the number is even
        if (i % 2 === 0) continue;

        // Reached here only if all checks passed (Odd and System Active)
        console.log(i);
    }
};

Summary

The continue statement is a control structure based on the concept of “excluding unnecessary items early.” By using this, you can avoid deep nested structures like “if it is X, then process” and instead write flat, readable code that says “if it is Y, skip it.”

よかったらシェアしてね!
  • URLをコピーしました!
  • URLをコピーしました!

この記事を書いた人

私が勉強したこと、実践したこと、してることを書いているブログです。
主に資産運用について書いていたのですが、
最近はプログラミングに興味があるので、今はそればっかりです。

目次