Break and continue statements

Although looping statements have conditional statements to exit the loop, there may be times when you need to exit from a loop halfway through. Both the 'break' and 'continue' statements provide more flexibility within a loop.

The 'break' statement is used to exit a loop completely. Upon reaching a 'break' statement, program control will skip to the next line of code following the loop. The 'break' statement might be used inside of an infinite loop as a means to exit. An example might look something like this:

while(True)
	{
	generic_statements;
	if (quitFlag == True) 
		break;
	generic_statements;
	}

The 'continue' statement is similar to the 'break' statement, except that instead of exiting the loop, it causes execution to return to the beginning of the loop. In a while loop, this means that the conditional statement will be evaluated, and the body of the loop will potentially be executed again. In a for loop, the increment statement will be executed, and then the conditional statement will be evaluated.

The 'continue' statement is often used when you don't want to apply the loop to a specific situation, but you want to continue with the loop. With the counting example, the extremely superstitious may wish to avoid printing the number '13' to the screen. This could be accomplished by altering the code to:

<html>
<head>
<title>Continue Example</title>
>/head>
<body bgcolor = "#FFFFFF">
<script language = "JavaScript">
<!-- Hide code

// Loop from 1 to 20, skipping 13
// Analysis

for(var x=1; x <= 20; x++)
	{	
	if(x == 13)
		continue;
	document.writeln(x + "<br>"); 
	}

//  End script -->
</script>
</body>
</html>