Is using labels in JavaScript bad practice?

二次信任 提交于 2019-11-27 04:18:44

问题


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?


回答1:


Those are loop breaker identifiers. They are useful if you have nested loops (loops inside loops) and using these identifiers, you can conditionally specify when and which loop to break out from.




回答2:


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.




回答3:


Avoid using labels

Labels are not very commonly used in JavaScript since they make programs harder to read and understand. As much as possible, avoid using labels and, depending on the cases, prefer calling functions or throwing an error.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/label




回答4:


labelled breaks can break out of any block of code not just loops

<p id="test1"></p>
<p id="test2"></p>
<p id="test3"></p>
<p id="test4"></p>
<p id="test5"></p>

test: {                            
    document.getElementById('test1').innerHTML = "test 1 passed";
    document.getElementById('test2').innerHTML = "test 2 passed";
    document.getElementById('test3').innerHTML = "test 3 passed";
    break test;
    document.getElementById('test4').innerHTML = "test 4 passed";
    document.getElementById('test5').innerHTML = "test 5 passed";
}

result:

test 1 passed

test 2 passed

test 3 passed



来源:https://stackoverflow.com/questions/4906762/is-using-labels-in-javascript-bad-practice

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!