Page 381 - Webapplication11_C11_Flipbook
P. 381

The break is a keyword in JavaScript which is used for bringing the program control out of the loop. The break statement
                 halts the execution of a loop and program flow switches to the statement after the loop. A single break statement will
                 break out of only one loop.








                                                                                  Condi onal Code
                                                                      True
                                                   Condi on                            Break
                                                                                     statement

                                                  False


                 The following example shows the use of break statement in a loop:
                 Example:

                   <HTML>
                   <BODY text="blue">

                   <H2 style="color:red;">Using a loop with a break statement.</H2>
                   <SCRIPT>
                   for(i=1;i<10;i++) {
                     if (i%3==0)

                       { break; }
                     else {
                        document.write("The number is " + i + "<br> <br>"); }
                   }//for ends
                   document.write("Statement outside for loop");

                   </SCRIPT>
                   </BODY>
                   </HTML>
                 On running the above program, we get the following output:



















                 Let us try to understand this example. The variable ‘i’ is initialised with the value 1. Since 1 is not divisible by 3, the if
                 condition turns out to be false and so the else block is executed—“The number is 1” is displayed on screen. The same
                 happens when i=2.

                                                                                                  JavaScript Part 1  379
   376   377   378   379   380   381   382   383   384   385   386