Difference Between Break and Continue in JavaScript

There is a significant difference between the Break and continue statements in JavaScript.

The break statement terminates a while or for loop completely. The continue statement terminates the execution of the statements within a while or for loop and continues the loop in the next iteration. The following two examples demonstrate how these statements are used.

Function Using Break

// Function to check if a value is numeric
function isNumeric(value) {
    return !isNaN(value);
}

// Function to print an error message for non-numeric values and break the loop
function handleErrorWithBreak(value) {
    console.log(value.toString() + " is not numeric. Stopping execution.");
}

// Function to process array and sum numeric values, breaking on non-numeric
function sumArrayElementsWithBreak(parmArray) {
    let sum = 0;
    for (let i = 0; i < 10; i++) {
        if (!isNumeric(parmArray[i])) {
            handleErrorWithBreak(parmArray[i]);
            break; // Exit loop when a non-numeric value is encountered
        }
        sum += parmArray[i];
    }
    return sum;
}

// Main function that calls the break version
function break4errorWithBreak(parmArray) {
    return sumArrayElementsWithBreak(parmArray);
}

JavaScript

Copy

Function using Continue

// Function to check if a value is numeric
function isNumeric(value) {
    return !isNaN(value);
}

// Function to print an error message for non-numeric values but continue loop
function handleErrorWithContinue(value) {
    console.log(value.toString() + " is not numeric. Continuing with the next number.");
}

// Function to process array and sum numeric values, skipping non-numeric values
function sumArrayElementsWithContinue(parmArray) {
    let sum = 0;
    for (let i = 0; i < 10; i++) {
        if (!isNumeric(parmArray[i])) {
            handleErrorWithContinue(parmArray[i]);
            continue; // Skip to the next iteration when a non-numeric value is encountered
        }
        sum += parmArray[i];
    }
    return sum;
}

// Main function that calls the continue version
function break4errorWithContinue(parmArray) {
    return sumArrayElementsWithContinue(parmArray);
}

JavaScript

Copy

Conclusion

  • break: Stops execution as soon as a non-numeric value is found.
  • continue: Skips non-numeric values and continues summing the rest of the array.

Up Next
    Ebook Download
    View all
    Learn
    View all