Home Articles FAQs XREF Games Software Instant Books About Feedback Search Site-Map
irt.org logo

Q1617 How do I exit out of a loop in JavaScript?

irt.org | Knowledge Base | JavaScript | General | Q1617 [ previous next ]

Q1617 How do I exit out of a loop in JavaScript?

Either by using the break or continue statement. the break statement immediately exits the loop and then continues execution from the next statement after the loop. Continue immeadiately exits the current loop and then attempts to start the loop again, depending on the loop pre-conditions.

For example, the following exits the loop when the counter reaches 99:

<script language="JavaScript"><!--
for (var counter=0;;counter++) { // an infinite loop
  document.write(counter + '<br>');
  if (counter == 100) break;
}
//--></script>

Whereas the following only outputs odd integers between 0 and 100:

<script language="JavaScript"><!--
for (var counter=0; counter<100; counter++) {
  if (counter % 2 == 0)
    continue;
  document.write(counter + '<br>');
}
//--></script>

Provide feedback ...
AddThis Social Bookmark Button

Provide feedback ... AddThis Social Bookmark Button


Last Updated: 30th March 2008. Maintained by: Martin Webb and Michel Plungjan
irt.org liability, trademark, document use, privacy statement and software licensing rules apply.
Copyright © 1996-2008 irt.org, All Rights Reserved.