break
The break
statement causes the innermost
enclosing loop or a switch
statement to exit
immediately. Its syntax is simple:
break;
Because it causes a loop or switch
to exit, this
form of the break
statement is legal only if it
appears within one of these statements.
ECMAScript v3 and JavaScript 1.2 allow the break
keyword
to be followed by the name of a label:
break labelname
;
Note that labelname
is simply an
identifier; it is not followed by a colon, as it would be when
defining a labeled statement.
When break
is used with a label, it jumps to the
end of, or terminates, the named statement, which may be any
enclosing statement. The named statement need not be a loop or
switch
; a break
statement used
with a label need not even be contained within a loop or
switch
. The only restriction on the label of the
break
statement is that it name an
enclosing statement. The label can name an
if
statement, for example, or even a block of
statements grouped within curly braces, for the sole purpose of
naming the block with a label.
As discussed in Chapter 2, a newline is not allowed between the
break
keyword and the
labelname
. This is an oddity of JavaScript
syntax caused by its automatic insertion of omitted semicolons. If
you break a line of code between the break
keyword
and the following label, JavaScript assumes you meant to use the
simple, unlabeled form of the statement and adds a semicolon for you.
We’ve already seen examples of the break
statement within a switch
statement. ...
Get JavaScript: The Definitive Guide, Fourth Edition 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.