3 ms·
This is not unique to JavaScript. You can do this in many languages, including Java. In fact, the JDK source is littered with usages of this "pattern", but wi
by dljsjr 13y ago
This is not unique to JavaScript. You can do this in many languages, including Java. In fact, the JDK source is littered with usages of this "pattern", but with loops instead of if statements. It is frequently used as a technique to capture a terminal event in an inner loop that requires termination of the entire nested looping construct; in other words, the label is applied to the outer loop but the break statement occurs somewhere in an inner loop.
99.9% of the time, when I'm writing nested loops and I find myself needing the ability to kill the outer loop from within the inner loop, this is a flag that I need to refactor or re-evaluate my design, not start using labels and breaks.
- stephengillie 13y agoThis method of breaking loops from the inside reminds me of the code obfuscation referenced in the HDD Hacking article [1]. Making code hard to read definitely seems like one use of this technique. So I suppose the converse is true -- if you want your code to be easily readable, refactoring is a better way of solving the problem than label-loop-terminating. [1]https://news.ycombinator.com/item?id=6148347 https://news.ycombinator.com/item?id=6148347
- jmilkbal 13y agoTo the contrary, labels and breaks are the better design because they are far clearer than testing for termination in each outer loop. Get more than two loops deep and your problem suddenly becomes unmanageable without labels and breaks. However, if there are other actions like logging or reporting that are occurring it may be better to not use them. Here's some Ada: Outer: loop Inner: loop Handle_Head: declare Head : Human_Head; begin Acquire_Head (Head); -- Entry will block until head is acquired. exit Inner when Head = No_Head; exit Outer when Head.Exploded; Log ("Head unexploded."); exception when Brain_Error => Log ("Brain deficiency detected."); end Handle_Head; end loop Inner; Log ("Head exploded."); end loop Outer;
- dljsjr 13y agoI'd argue that if you're more than 2 loops deep then you should, as I stated before, seriously evaluate your design decisions. And, should you do so and end up in the same place, you may have stumbled upon that 0.1% of the time that I left wiggle room for in my first claim.
- marshray 13y agoYou know, returning from within the loop counts as breaking out of it too. I get the feeling that your experience as a programmer is very different from mine.