javascriptlabeled-statements

Should I Ever Use Labels In Javascript? (If So, When?)


Backstory: Once again I was reading in my Javascript book and I bumped into something that the book didn't explain very well, and that I wasn't able to find any good examples of online.

Example from Book:

parser:
    while(token != null) {
    // Code omitted here
}

The only paragraph used to explain this code said that by using a label I could refer to a statement elsewhere in my code and that labels are "commonly" used for loops. I've never seen a label used before let alone "commonly."

My question is: Are labels used and if so what is a good example of a place where I would want to use one?


Solution

  • The only time I've really seen it is in a nested loop or if statement you can use labels to break to a specific one for example:

    function foo ()
    {
        dance:
        for(var k = 0; k < 4; k++){
            for(var m = 0; m < 4; m++){
                if(m == 2){
                    break dance;
                }
            }
        }
    }
    

    the label "dance" lets you break to that point specifically if m == 2.

    In my experience I would not say they are very common.

    Example taken from here: How to break nested loops in javascript?

    Perhaps better example here: Best way to break from nested loops in Javascript? at the second answer.