JavaScript Tutorial





Español Français 中文 Deutsch Portuguese Japanese nederlands
   
 
Java-Script Tutorial
Introduction Introduction
Variables Variables
Operators Operators
Statements Statements
Loops Loops
Functions Functions
Objects Objects
Arrays Arrays
Cookies JS Cookies
Browser Objects Browser Objects
Form DOM Form DOM
Style Objects DOM Style Objects
Forums Ask Your Doubts
Scraps More about Javascript
Feedback Feedback
 




Break Statement


Tutorials Javascript

Topic

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



Explanation
        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 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.





A Note
Javascript (JS) is one of the most used languages in the world. Some times spelled as Java Script. Hope you enjoy this tutorial. Do send your feedback or suggestions on this javascript or java script tutorial. This is a copyright content.

Other Links

web hosting