JavaScript Loop Control - Java Script

What is JavaScript Loop Control?

JavaScript ‘Loop control’ enables us to have control over the loops. You may encounter a situation where you want to exit the loop without reaching its end. In other words, you may require to skip a block of statements and start the next iteration of loop. There may be a situation when you need to come out of a loop without reaching its bottom

In order to handle the above situations JavaScript makes use of break and continue statements.Let’s discuss them in detail:

What is JavaScript Break Statement?

Using break statement, we can break the loop and continue the execution of rest of code that follows after the loop. We have already discussed the use of break statement in Switch. We can stop the particular case by placing the break statement at the end of the case.

Flow Chart of Loop Control:

The flow chart of a break statement is shown below−
flow chart of a break statement
Example

The below example explains the usage of a break statement with a while loop. Observe how the loop comes out early once x reaches 5 and reaches to document.write (..) statement just before to the closing curly brace −
Output:
JavaScript Loop Control

What is JavaScript continue Statement?

The break statement stops the execution of loop where as the continue statement starts the next iteration of the loop leaving the remaining bock of code. When a continue statement is found, the condition is re-evaluated. If it returns true then it starts the next iteration, if it returns false the control exits the loop.

Example

The below example explains the usage of a continue statement with a while loop. Observe how the continue statement skips the printing of the variable x when the index reaches 5.

Output:
JavaScript Loop Control

How to use labels to control the flow?

The label statement can be used with continue and break statements to control the flow more accurately. A label is simply an identifier

followed by a colon (:) that is applicable to group of statements. Let us see how to use labels with break and continue statements with the help of below examples:

Note –Make sure we should not place any other statement between a label name and corresponding loop.

Example 1
The below example illustrates how to implement Label with a break statement.
Output:
how to implement Label with a break statement.

Example 2

This will produce the folowing output:
how to implement Label with a break statement.

All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd DMCA.com Protection Status

Java Script Topics