Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do labels exist?

Tags:

javascript

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.

like image 660
P.Brian.Mackey Avatar asked Oct 24 '11 21:10

P.Brian.Mackey


2 Answers

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)

like image 190
SLaks Avatar answered Sep 18 '22 18:09

SLaks


Yup, they exist for GOTOs and SWITCH statements. I basically see them used for nothing else, and would never consider labeling a section of code just for the fun of it..

like image 29
Mike Christensen Avatar answered Sep 17 '22 18:09

Mike Christensen