The Break Statement
- The break statement can be used to jump out of a loop even when the condition is true.
- The break statement breaks the loop and continues executing all the code after the loop(if any):
1 2 3 4 5 6 | <script> var i; for(i = 0; i <= 5; i++){ text += "The number is:"+i; } </script> |
OUTPUT
1 2 3 4 5 6 | The number is: 0 The number is: 1 The number is: 2 The number is: 3 The number is: 4 The number is: 5 |
This time though, we want to stop execution of the loop when i become 3. To do so, we are inserting another conditional checking i, and if the test passes, we will break execution of the loop:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | <html> <body> <script> var i; for(i = 0; i <= 5; i++){ if (i === 3) { break; } text += "The number is:"+i; } } //here the loop breaks out when i becomes 3 </script> </body> </html> |
OUTPUT
1 2 3 | The number is: 0 The number is: 1 The number is: 2 |
The Continue Statement
The continue statement breaks one iteration (in the loop), if a specified condition occurs, and continues with the next iteration in the loop.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | <html> <body> <script> var i; for (i = 0; i <= 5; i++) { if (i === 3) { continue; } text += "The number is:" + i; } //here i===3 condition is skipped </script> </body> </html> |
OUTPUT
1 2 3 4 5 | The number is: 0 The number is: 1 The number is: 2 The number is: 4 The number is: 5 |