break Statements

By: Dusty Arlia
Published on Saturday, April 13, 2013, 05:47 PM
Last Updated on Sunday, July 05, 2015 at 9:07 PM
Total Updates: 3

JavaScript break statements exit out of loops and switches. When the break statement executes, it exits the block statement it is currently in. What this means is that whatever statement comes after the block statement you are "breaking out of", gets executed and your program continues on as normal. Here is the basic syntax of a break statement:


There is also a labeled form:

break [Optional label name];

You can include a label name after the break keyword as an option to exit out of an enclosing labeled statement. In the break statement's labeled form, you can "break out" of other block statements besides loops and switches. This excludes functions. You are not allowed to label a function definition and you are not allowed to break out of an executing function.

Both of these statements will exit out of the enclosing statement, but the second one will exit out of a labeled statement that encloses it. This is particularly helpful and most commonely used when your statement is nested inside one or more different block statements. Here is an example of a labeled break statement (notice that the colon (:) is left out):

break slideshowLoop;   //the label name is slideshowLoop

When using labels, make sure you're following the proper naming conventions. Labels follow the same naming rules as variables and functions, but have a separate namespace. What this means is that you can use the same identifier for your label as you could for your variable or function without getting an error.

Never put a line break in between the break keyword and the label name. This will result with the JavaScript interpreter automatically inserting a semicolon. The JavaScript interpreter will assume you meant to use the break statement without a label name.