Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the point of using labels in javascript (label: stuff here) outside switches?

Tags:

javascript

What is the point of using labels in javascript (label: stuff here) outside switches?

like image 978
DarkLightA Avatar asked Dec 28 '10 15:12

DarkLightA


2 Answers

You can use them as goto statements on break and continue, though admittedly you rarely see this in practice. You can find a few examples here.

Here's a quick one:

myLabel:
for(var i=0; i<10; i++) {
  if(i==0) continue myLabel; //start over for some reason
}    
like image 110
Nick Craver Avatar answered Nov 15 '22 08:11

Nick Craver


They're also useful in loops:

var x, y;

outer: for (x = 0; x < 10; ++x) {
    for (y = 0; y < 10; ++y) {
       if (checkSomething(x, y)) {
           break outer;
       }
    }
}

...which breaks out of both loops if checkSomething returns true.

I've never actually coded one of those, I've always split the inner loop off to a function or similar, but you can do it that way. Some people consider it bad style, akin to goto (which JavaScript doesn't have).

like image 37
T.J. Crowder Avatar answered Nov 15 '22 08:11

T.J. Crowder