JavaScript break and continue Statements

If you are creating a script using the JavaScript loop statements, you may have to terminate a loop when a particular condition occurs. For example, you may want to display a group of 10 records in a webpage and allow the next 10 records to appear in next page only when a user clicks next button. You can do this with a counter variable in the loop. Every time this counter value is divisible by 10 the loop must be terminated. In such situation you will need JavaScript Break and Continue statements.

JavaScript break Statement

JavaScript Break statement gives you the flexibility to break a JavaScript loop.  It is done by associating break statement with a condition. Break Statement terminates innermost loop in which break statement is given without executing remaining iterations.

Suppose you have used a loop that must run 10 times. In 5th iteration a condition occurs when you have to terminate the loop. All you need to do is add the break statement with this condition. It is specified with if conditional construct. After 5th iteration the loop will break and the next statement after loop will execute. The rest of 5 iterations will not execute.

Example- display first 5 even numbers in given list using while loop with break statement.

<SCRIPT LANGUAGE="javascript">
var numArray= new Array(2,3,6,7,9,11,2,88,5,3,20,43,5,66,8,222,132);
ctr=0;
count=0;
while ( ctr<17)
{
	if (numArray[ctr]%2==0)
	{
	document.write( "value at "+ctr+" is "+numArray[ctr]+"<br>");
	count++;
	}
	if (count==5)
			break;
	ctr++;
}
document.write(  "These are the first five even numbers of given list<BR>");
</SCRIPT>

In the above coding example the loop is terminated with a break statement as soon as the count variable becomes 5. It is incremented each time an even number is encountered in the array numArray.

Continue Statement

Continue statement is totally opposite of JavaScript Break Statement. In the block of the loop statements when continue is encountered, the control ignores all the following statements. The loop control goes back to the header of loop and begins with the next iteration. Similar to the Break statement the continue statement must be linked with a condition using if conditional construct.

Example- display even numbers after 5th element in the given list using continue in a for loop

<SCRIPT LANGUAGE="javascript">
var numArray= new Array(2,3,6,7,9,11,2,88,5,3,20,43,5,66,8,222,132);
ctr=0;
for  (ctr=0;ctr<17;ctr++)
{
	if (ctr<5)
	{
		continue;
	}
	if (numArray[ctr]%2==0)
		document.write(  ctr +"value is "+numArray[ctr]+"<br>");
}

document.write(  "These are the even numbers after fifth element");
</SCRIPT>

In this example the first five iterations will be executed without checking the number for being even. This is done with continue in the loop with condition (ctr<5). After fifth iteration remaining array elements are checked and printed if they are even.