ManticMoo.COM All Articles Jeff's Articles
Jeffrey P. Bigham

Putting a label at the end of a code block

Jeffrey P. Bigham

Related Ads

Today, I was writing Javascript with a nested loop. On a certain condition, I wanted the code to break out of the inner loop and skip to the next iteration of the outer loop. I thought, incorrectly, that I could just naively use a label for this purpose by putting the label at the end of the outer loop and breaking to it from the inner loop. It would have looked like this:


for(var i=0; i<length; i++) {
   for(var j=0; j<length; j++) {
      ...
      if(condition) {
         break my_label;
      }
   }
my_label:
}

The Javascript interpreter barfed on this, however, because *apparently* it requires an actual statement to come after label definitions. In this situation, I don't want any statement to be executed and I can't just put the label at the beginning of the outer loop because I want i to be incremented and checked against the loop condition. To fix this, I just wrote continue as the statement. This is essentially a no-op, but it works! Below is the altered version of the code.


for(var i=0; i<length; i++) {
   for(var j=0; j<length; j++) {
      ...
      if(condition) {
         break my_label;
      }
   }
my_label:
   continue;
}

Jeffrey P. Bigham
ManticMoo.COM All Articles Jeff's Articles