JavaScript » Statements » break

Syntax:
break [ label ]

The break statement can be used to terminate a current loop, switch or label statement and pass control to the statement immediately following it.

Examples

Code:
var i = 0
while (i < 10)
{
   document.write(i);
   if (i==7)
   {
      document.write("the counter has reached " + i);
      break;
   }
   i++;
}
Explanation:

This example starts a loop printing the numbers from 1 to 10, buts exits when it reaches 7 with an appropriate message.

Code:
outer_loop:
for(i=0; i<3; i++)
{
   document.write("<BR>" + "outer " + i + ":   ");
   for(j=0; j<5; j++)
   {
      document.write("inner " + j + " ");
      if(j==x)
         break outer_loop;
   }
}
Explanation:

The break statement can also be used with a label as in this example of two counts, one nested within the other, which will be ended if the inner counter variable is equal to the variable 'x'.

Code:
even_number:
if(i%2==0)
{
   if(i==12)
      break even_number;
   document.write(i);
}
Explanation:

While the break statement on its own can only be used to exit a loop, the optional label can be added to break to exit any kind of statement. This example tests for an even number and, whenever it finds one, displays it, unless that number is 12.