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?
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.
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).
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 .
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With