Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is using labels in JavaScript bad practice?

I just found out about using label s in JavaScript, such as:

for (var i in team) {     if(i === "something") {         break doThis: //Goto the label     } else {         doThat();     } }  doThis: //Label doIt(); 

I've not heard about this until now and I can't find much information online about it and I'm beginning to think there is a reason for that.

It seems to me like this is similar to a GOTO statement in other languages and would be considered bad practice. Would I be right in assuming this?

like image 327
Ryan Avatar asked Feb 05 '11 12:02

Ryan


People also ask

Why are labels bad in programming?

It's difficult to read code containing break s to a label. Also, a label can be accidentally moved, or code inserted at an incorrect location with respect to a label. The compiler is not able to warn you of these effects since the code remains syntactically valid. Code that's difficult to read is difficult to maintain.

Should I use labels in Java?

Yes, you should avoid using label unless there's a specific reason to use them (the example of it simplifying implementation of an algorithm is pertinent).

What is the use of label in JavaScript?

Description. You can use a label to identify a loop, and then use the break or continue statements to indicate whether a program should interrupt the loop or continue its execution. Note that JavaScript has no goto statement, you can only use labels with break or continue .


1 Answers

The labels in JavaScript are used mainly with break, or continue in nested loops to be able to break the outer, or continue the outer loop from the code inside inner loop:

    outer:     for (let i = 0; i < 10; i++)     {         let k = 5;        for (let j = 0; j < 10; j++) // inner loop           if (j > 5)                 break; // inner            else                continue outer;  // it will go to next iteration of outer loop     } 

If you used continue without 'outer' label, it would go to the next iteration of inner loop. That's why there is a need for labels in Javascript.

like image 156
tdobek Avatar answered Sep 22 '22 21:09

tdobek