Search code examples
javascriptreadabilitycode-readability

Is it okay to use break with labels in javascript?


Is there any benefit of doing so and can it lead to readability concerns?


Solution

  • Labels are generally used in JavaScript to break from an outer loop. For example:

    while (true) {
        while (true) {
            if (someCondition) break;
        }
    }
    

    In this program you'll only break from the inner loop. The outer loop will loop infinitely. Sometimes however you may wish to break from the outer loop instead of the inner loop. You use labels for this purpose:

    loop: while (true) {
        while (true) {
            if (someCondition) break loop;
        }
    }
    

    That being said if you have lots of nested loops or switch cases then using labels does in fact help with code readability even though it may not actually affect the program itself.

    Take the code in this question for example: https://codereview.stackexchange.com/q/14532/15640

    Here we have a switch case in a for loop and although it using we never need to break out of the for loop labelling the loop and the switch case might help some people. For others it's just a distraction.

    In the end it boils down to your style of programming. Beginners usually like to label everything. More experience programmers find too many comments and labels annoying.

    Steve Yegge actually wrote an entire blog post on this. You may find it very interesting: http://steve-yegge.blogspot.in/2008/02/portrait-of-n00b.html

    Try coding without comments: http://www.codinghorror.com/blog/2008/07/coding-without-comments.html