The break Statement

Going hand-in-hand with the continue statement is the break statement. Whereas the continue statement forces another iteration, the break statement jumps you out of the loop completely!

You typically use the break statement in while, for, for ... in, and do ... while statements (and switch statements, which we've not covered yet).

In the following example, the first alert box (displaying a 1) is shown, after which the break statement comes into force and kicks you out of the loop:

<script language="JavaScript">
<!-- Cloaking device on!
var x = 0;
while (x < 10)
{
x++;
alert(x);
break;
alert("Never seen!");
}
// Cloaking device off -->
</script>

Again, the best way to use the break statement is in conjunction with an if

Get JavaScript™ 1.5 by Example now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.