JavaScript Labels

In order to better understand JavaScript’s labels let’s start by taking a look at what a Label actually is. As usual, let’s turn to MDN for the definition: “Any JavaScript identifier that is not a reserved word.”. Now we know that a label is an identifier. But what is it used for? Labels are used to“[prefix] a statement with an identifier which you can refer to.” Labels are usually used in JavaScript in conjunction with break and continue statements. Let’s take a look at an example:

var itemsPassed = 0;
var i, j;

top:
for (i = 0; i < items.length; i++){
  for (j = 0; j < tests.length; j++)
    if (!tests[j].pass(items[i]))
      continue top;
    itemsPassed++;
}

This function labels the top for loop as top. When “continue top” is called, the continue statement will not carry out the expected operation of continuing the nested for loop, but instead the outer one. This has given you the option to refer to different for loops by name (labels), and to carry out specific operations in specific ones regardless of which loop order of operations.

Let’s take a look at another example, this time using two labels and break statements:

var i, j;

loop1:
for (i = 0; i < 3; i++) {      //The first for statement is labeled "loop1"
   loop2:
   for (j = 0; j < 3; j++) {   //The second for statement is labeled "loop2"
      if (i == 1 && j == 1) {
         break loop1;
      }
      console.log("i = " + i + ", j = " + j);
   }
}

// Output is:
//   "i = 0, j = 0"
//   "i = 0, j = 1"
//   "i = 0, j = 2"
//   "i = 1, j = 0"

As you can see from this example, as both I and J reach the value of one, the break is called on the outer loop and we break out of it which skips the rest of the nested loop as well. As you can probably tell by now, this could be very useful when you need to loop through different sets and you would need to break out of everything if a specific result was reached. Now that you know how to use a nested loop, I would recommend that you don’t use Labels. The reason for this is probably the same reason that brought you to this page: most JavaScript programmers are simply not familiar or experienced with these and will find your code harder to read. Since most of the time we are not writing code for ourselves but for those coming afterwards, let’s try to make our code as simple and as straight forward as possible. But in case you do end up seeing someone’s code who has them, now at least you will know what they are. My last suggestion on this would be that if you do need to use labels, then I highly recommend leaving as many comments as you can explaining what you are doing.

Paulo Diniz