News for hackers. Stuff that matters.
Re:Use labels to break ifs in JavaScript by dljsjr on Wednesday August 07, 2013 @09:52AM (#6172790)
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.

Re:Use labels to break ifs in JavaScript by jmilkbal on Wednesday August 07, 2013 @11:48AM (#6173568)
To 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;
Re:Use labels to break ifs in JavaScript by dljsjr on Wednesday August 07, 2013 @01:14PM (#6174102)
I'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.

Re:Use labels to break ifs in JavaScript by stephengillie on Wednesday August 07, 2013 @10:07AM (#6172897)
This 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

Re:Use labels to break ifs in JavaScript by marshray on Wednesday August 07, 2013 @06:48PM (#6176201)
You 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.