Introduction:
Java Script Loop Control allows us to control the flow of loops. There are needs to control the loops flow at certain point in time, so Java Script has provided us the ways to control the flow through the statements known as break and continue like it was used in other programming language right from C Language.
Break Statement:
Break Statement will break the loop and continue executing the rest of the code that follows after the loop. As soon as the break statement is encountered the program control will come out of the loop and will execute the lines of code that are written outside the loop.
Continue Statement:
Continue Statement breaks the current iteration of a loop and will continue iterating the next iteration.
Example of Break Statement:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script type="text/javascript">
function breakfunc() {
var i = 0;
for (i = 0; i < 10; i++) {
if (i == 4) {
break;
}
document.write("The value of i is:" + i + "<br />");
}
document.write("<br />");
}
</script>
</head>
<body>
<input id="btnSubmit" type="button" value="button" onclick="breakfunc()" />
</body>
</html>
Output:
In this example we found that as soon as fourth iteration has encountered the
whole loop is terminated and rest of the code which are outside the loop executes.
Example of Continue Statement:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script type="text/javascript">
function confunc() {
var i = 0;
for (i = 0; i < 10; i++) {
if (i == 4) {
continue;
}
document.write("The value of i is:" + i + "<br />");
}
document.write("<br />");
}
</script>
</head>
<body> <div>
<input id="btnSubmit" type="button" value="button" onclick="confunc()" />
</div>
</body>
</html>
Output:
In this example we have found that as soon as fourth value is encountered the
control has skipped that particular iteration and moved onto the next iteration.
Conclusion:
In this article we gained knowledge about how to control the flow of loops with
the help of Break and Continue statement which are important part in
programming.
Leave Comment