The break and continue statements offer additional control over the code execution inside a loop.

They work great with the if statement because that combination lets a developer decide if there are some special conditions to leave or continue the loop execution. More precisely, a break statement exits the loop immediately and the execution continues with the first line after the loop; on the other hand a continue statement stops the loop immediately but it doesn't exit it, it actually continues from the top of the same loop; therefore it just skips the current loop count.

These examples show how both statements work:

var num;

for (var i=0; i<10; i++)  {

   if (i==6) {

      break;

   }

   text = text + "Counter: " + i + ", ";

}

for (var i=0; i<10; i++)  {

   if (i==6) {

      continue;

   }

   text = text + "Counter: " + i + ", ";

}

In the first example, the loop will completely stop executing after the iteration reaches the number "6", while in the following example number "6" is going to be skipped and the loop will continue with the following one.

Example

The example with break and continue statements in JavaScript:

 

›› go to examples ››