20.5. Labels

JavaScript supports labels, which can be used to mark statements for reference by other statements in other sections of a script. Labels have the following format:

<label_name>:

To use a label, place it before the statement you wish to identify with the label. For example, the following references the while loop with the label code_loop:

var x = 100;
code_loop:
while (x <= 1000) {
  // statement(s)
}

You can reference labels using the break statement to exit structures outside of the current structure. For example, both loops in the following code will be broken out of if the variable z ever equals 100:

var  x = 0, y = 0;
top_loop:
while (x <= 100) {
  while (y <= 50) {
    ...
    if (z == 100) break top_loop;
  }
}
/* execution resumes here after loops are complete or if
    z = 100 during the loops execution */

You can also use labels to mark blocks of code, as in the following example:

code_block: {
  // block of code here
}

The break statement can then be used to break out of the block, if necessary.

Get Web Standards Programmer's Reference: HTML, CSS, JavaScript®, Perl, Python®, and PHP 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.