Home » Online Computer Education » Learn Java Script, The break Statement and continue Statement, Lesson No. 26

Learn Java Script, The break Statement and continue Statement, Lesson No. 26

 

 

The break statement lets you terminate a label, switch, or loop. The script then continues processing with the statement that follows the label, switch, or loop statement that was broken out of.

The following example shows how to use the break statement to terminate the execution of a while loop. In this case, the break statement terminates the loop when the value of counter becomes equal to 5. Because there are no other statements following the while loop, script execution stops when it processes the break statement.

<HTML>
<HEAD>
<TITLE>Script 2.16 – Demonstration of the break
statement</TITLE>
</HEAD>
<BODY>
<SCRIPT LANGUAGE=”JavaScript” TYPE=”Text/JavaScript”>
<!– Start hiding JavaScript statements

var counter = 10;

document.write(“<B>Watch me count backwards!</B><BR>”);

while (counter > 0) {
counter;
document.write(“counter = “, counter , “<BR>”);
if (counter == 5 ) break;
}

// End hiding JavaScript statements –>
</SCRIPT>
</BODY>
</HTML>
The continue Statement
The continue statement is similar to the break statement. However, instead of terminating the execution of the loop, it merely terminates the current iteration of the loop.

The following example demonstrates how the continue statement can be used to terminate a given iteration of a loop. In this example, the loop examines four different cases as part of a switch statement. The result is that the iteration of the loop that occurs when the value assigned to the counter variable is equal to 8, 6, 4, or 2 is skipped, but processing of the loop does not terminate as would be the case when using a break statement. Instead, the loop simply continues with the next iteration.

<HTML>
<HEAD>
<TITLE>Script 2.17 – Demonstration of the continue
statement</TITLE>
</HEAD>
<BODY>
<SCRIPT LANGUAGE=”JavaScript” TYPE=”Text/JavaScript”>
<!– Start hiding JavaScript statements

var counter = 10;

document.write(“<B>Watch me count backwards!</B><BR>”);

CounterLoop:

while (counter > 0) {
counter;
switch (counter) {
case 8:
continue CounterLoop;
case 6:
continue CounterLoop;
case 4:
continue CounterLoop;
case 2:
continue CounterLoop;
}
document.write(“counter = “, counter , “<BR>”);
}
// End hiding JavaScript statements –>
</SCRIPT>
</BODY>
</HTML>

About

The main objective of this website is to provide quality study material to all students (from 1st to 12th class of any board) irrespective of their background as our motto is “Education for Everyone”. It is also a very good platform for teachers who want to share their valuable knowledge.

Leave a Reply

Your email address will not be published.