How To Control A Loop In Javascript

You may watch full clip here ad remember to subscribe;

Watch now!
Let’s discuss how to control your loop in javascript program, here we will discuss on the the use of break and continue statements,when you wish to come out of the loop without reaching the bottom or you just wish to skip a part of your code block and start a next iteration of the loop, remember to follow us in our social media platforms for more tutorials and live sessions we hold;
1. Break statement
It is applied when you wish to exit the loop early, lets have a syntax for break statement.
var x=1;
while(x<20)
{
if(x==5){
break; //it breaks out of loop completely
}
x=x=1;
document.write(x+ “<br />”);
}

2. CONTINUE STATEMENT

Continue statement tells the interpreter to skip the remaining code block and start a new iteration immediately. When it is encountered in a program it flows to the top to check the expression immediately and if the condition remains true it starts the iteration otherwise it comes out of the loop. Let’s have a syntax for a continue statement.

var x=1;
while(x<10)
{
x=x+1;
if(x==5){
continue;
}
document.write(x+ "<br />");
}

It will produce;
2
3
4
6
7
8
9
10
Use different variables and values and try it yourself

Using Labels To Control The Flow Of Th Loop

Label- it refers to an identifier followed by a colon, it is applied to a block of code or statement.

-There should not be any line breaks between the break or continue statement and its label name, there should not be any other statement between a label name and associated loop. Let’s have an example.

outerloop: this is the label name
for(var m=0; m<5; m++)
{
document.write("outerloop: "+ m +"<br />");
innerloop:
for(var p=0; p<5; p++)
{
if(p>3)break; //it quits the innermost loop
if(m==2) break innerloop;
if(m==4)break outerloop; //it quits the outerloop
document.write("innerloop:"+p+" <br />");
}
}

Thanks for reading through my tutorial on how to control your looping, next we will discuss very important part of this programming language called FUNCTIONS, ensure you don’t miss out by following our tutorials on our social media platforms. See you in our next tutorial.