MakeW3web

JavaScript Break and continue

`break` and `continue` are loop control statements in JavaScript that allow you to manage the flow of your loops more effectively.

  1. `break` statement:

The `break` statement is used to exit a loop early before its normal termination. When a `break` statement is encountered within a loop, the loop stops executing immediately, and the program continues executing the code after the loop.

Example:

for (let i = 1; i <= 10; i++) {
  if (i === 6) {
    break;
  }
  console.log(i);
}
// Output:
// 1
// 2
// 3
// 4
// 5

In this example, the `for` loop starts with `i = 1` and continues until `i = 10`. However, when `i` reaches 6, the `break` statement is executed, and the loop stops immediately. The numbers 6 to 10 are not printed.

  1. `continue` statement:

The `continue` statement is used to skip the current iteration of a loop and proceed to the next iteration. When a `continue` statement is encountered within a loop, the rest of the code within the loop's body for the current iteration is skipped, and the loop proceeds with the next iteration.

Example:

for (let i = 1; i <= 5; i++) {
  if (i === 3) {
    continue;
  }
  console.log(i);
}
// Output:
// 1
// 2
// 4
// 5

In this example, the `for` loop starts with `i = 1` and continues until `i = 5`. When `i` reaches 3, the `continue` statement is executed, and the current iteration is skipped. The rest of the loop's body is not executed for `i = 3`, and the loop proceeds with the next iteration. The number 3 is not printed.

Both `break` and `continue` statements give you more control over the flow of your loops. Using these statements effectively can help you optimize your code and make it more readable, especially when working with complex or nested loops.

Was this page helpful?