Continue and break statement - skipping a loop iteration - breaking out of a loop in javascript
continue and break statement, skipping a loop iteration, breaking out of a loop in javascript
JavaScript break And continue Statements For LoopsGo to JavaScript break And continue Statements For LoopsJavaScript tutorialGo to JavaScript tutorialWeb development tutorialsGo to web development tutorialsHomepage

Main navigation links of JavaScript Tutorial section

JavaScript break And continue Statements For Loops

JavaScript provides commands through which iterations of a loop can be skipped or stopped. These commands are most commonly used along with an if statement inside the loop.

  • continue: causes the iteration to be skipped
  • break: causes the loop to stop and program execution to begin at the statement immediately following the loop.

For example, continue can be employed to display only the even numbers between 1 to 20, skipping the odd numbers.

var msg = "";
for (var x = 0; x <=20; x++)
   {
   if (x%2)
      {
      continue;
      }
   msg = msg + x + "\n";
   }
alert(msg);

Click here to check the results

The condition in if checks for a remainder when variable x is divided by 2. Thus, for odd numbers, the condition will be 'true' and the loop will be skipped because of continue.


Similarly, break is employed to stop loop iterations completely.

var msg = "";
var t = 1;
while (t <= 10)
   {
   if (t == 8)
      {
      break;
      }
   msg = msg + t + "\n";
   t++;
   }
alert(msg);

Click here to check the results

Loop iteration stops when the value of variable t equals 8.



Assignments
  1. In the code below, which numbers are displayed in the alert box?
    var msg = "";
    for (var x = 0; x < 10; x++)
       {
       if (x == 5 || x == 7)
          {
          continue;
          }
       msg = msg + x + "\n";
       }
    alert(msg);
    
  2. How can you display the odd numbers between 1 to 20 WITHOUT the use of continue?
   Click here for possible answers


Online Workspace

Back Next


AddThis Social Bookmark Button
Page contents: Continue and break statement - skipping a loop iteration - breaking out of a loop in javascript

Page URL: http://www.webdevelopersnotes.com/tutorials/javascript/ javascript_break_continue_loop_statements.php3



Join Mailing List


Feedback/Questions




50+ web hosting FAQs

Search engine for your website

Free software from Google - The Google Pack Collection

Create your own search engine
Search WebDevelopersNotes.com