This site uses tracking technologies. You may opt in or opt out of the use of these technologies.

Back to Javascript

Breaking and continuing loops

In JavaScript, you can control the flow of loops using break and continue statements

In JavaScript, you can control the flow of loops using break and continue statements:

  1. break statement:

    • Exits the loop entirely.

    • Stops executing any further iterations in a loop.

  2. continue statement:

    • Skips the current iteration and continues with the next one.

    • The loop does not terminate, but moves to the next iteration.

Here's a breakdown with examples:

break Statement Example

for (let i = 0; i < 10; i++) {
if (i === 5) {
break; // Exit the loop when i equals 5
}
console.log(i); // Outputs: 0, 1, 2, 3, 4
}

In this example:

  • When i reaches 5, the break statement stops the loop.

continue Statement Example

for (let i = 0; i < 10; i++) {
if (i % 2 === 0) {
continue; // Skip even numbers
}
console.log(i); // Outputs: 1, 3, 5, 7, 9
}

In this example:

  • The continue statement skips even numbers and moves to the next iteration when i is even.

Both statements can also be used in while and do...while loops to control the loop flow in the same way.