Search code examples
javascriptlabeled-statements

Why do labels exist?


Why do labels exist in javascript?

var i = 0;

usefulLabel://why do I exist?
while(i <= 10){
    document.writeln(i);
    i++;
    if(i > 5)
        break;// usefulLabel;
}

The above code doesn't appear to need a label at all (it works with or without the commented label name). And Considering Douglas Crockford has not condemned them entirely:

Labels

Statement labels are optional. Only these statements should be labeled: while, do, for, switch.

Are they ever considered a good practice to implement? To me, these things look eerily close to the infamous goto statement in some languages.


Solution

  • If you want to break out of the outermost loop from a nested loop, you need a label.
    If you end up needing that, you should consider refactoring the code to make it simpler. (although that won't always be possible)