Break Statement

How to exit from a loop in-between an iteration in javascript?


Break is a statement used to exit or terminate a loop in execution. It is used in "for, while, do-while" looping statements. Break statement is used mostly with a conditional statement inside the loop. When the condition satisfies the control breaks/terminates from the loop and moves to the next line below the loop.
For an example, we will use a for loop that prints 1 to 5 but will use break or exit the loop iteration when i is 3.


<script language="javascript">
for(var i=0; i<5; i++)
if(i == 3)
document.write("i is - "+i);
document.write(" --------- After Looping------ ");


The example worked as follows,
a) "for loop" has five iterations from i=0 to i=4.
b) It executes document.write at every iteration for i=0,i=1,i=2.
c) when i is 3 the condition above document.write becomes true and so it is called.
d) break statement exits or terminates the looping sequence and brings the control to the line next to the end of loop.

Ask Questions

Ask Question