break statement:
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.
Example Code:
<script language="javascript">
for(var i=0; i<5; i++)
{
if(i == 3)
break;
document.write("i is - "+i);
}
document.write(" --------- After Looping------ ");
</script>
Result:
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 break
statement is called.
d) break statement exits or terminates the looping sequence and brings the control to the
line next to the end of loop.
|