JavaScript Breaks & Continue


The Break Statement

The break statement can also be used to jump out of a loop.

<script type="text/javascript">
   for (var i=1 ; i<=5 ;i++)
   {
      if (i == 4)
      {
        break;
       }
       document.write(i + "<br/>");
     }
</script>
Output
1
2
3

The Continue Statement

The continue statement breaks one iteration (in the loop), if a specified condition occurs, and continues with the next iteration in the loop.

<script type="text/javascript">
   for (var i=1 ; i<=5 ;i++)
   {
      if (i == 4)
      {
        continue;
       }
       document.write(i + "<br/>");
     }
</script>
Output


Using Labels

To label JavaScript statements you precede the statements with a label name and a colon.

Syntax

label:
statements

The break and the continue statements are the only JavaScript statements that can "jump out of" a code block.

Syntax

break labelname;

continue labelname;

The continue statement (with or without a label reference) can only be used inside a loop.

The break statement, without a label reference, can only be used inside a loop or a switch.

Example

<script type="text/javascript">
student = ["Ashwani", "Sachin", "Deepak"];
names = "";
student_name_list: {
    names += student[0] + "<br>";
    names += student[1] + "<br>";
    break student_name_list;
    names += student[2] + "<br>";
    names += student[3] + "<br>";
}
document.write(names);
</script>
Output
Ashwani
Sachin

Share this article on