javascriptlabeled-statements

Javascript Label


Mozilla Developer Network states that

Statement 1 : "The labeled statement can be used with break or continue statements. It is prefixing a statement with an identifier which you can refer to."

Statement 2 : "break can be used with any labeled statement, and continue can be used with looping labeled statements."

Question : Does javascript allow labeling any statement or just the loops. If it's just the loop statement? what is relevance of "Statement 2" above from MDN


Solution

  • You can label any statement, including a labeled statement. Labels only do something useful when somewhere inside the labeled statement is a context in which break or continue make sense.

    Thus

    pointless: var x = 0;
    

    is syntactically OK but the label doesn't (can't) do anything.

    To be able to break to a label, the break needs to be inside the labeled statement. A break cannot be "inside" a var declaration as in the example above, which is why it's not useful. However, this works, and is the typical use of break:

    outerLoop: for (var i = 0; i < matrix.length; ++i) {
      for (var j = 0; j < matrix[i].length; ++j) {
        var inMatrix = matrix[i][j];
        if (somethingWeird(inMatrix))
          break outerLoop;
      }
    }
    

    If you want to break out of a nested loop structure without having some awkward flags to test, you can use a labeled statement like that.

    The slightly mysterious note from MDN that you mention about break being available from any sort of statement just means that you can break from things that aren't loops:

    someLabel: if (condition(something)) {
      // code code code
      if (shouldGiveUp())
        break someLabel;
      // more code
    }
    

    That works like a "goto" to the next statement after the outer if statement. You can't do that with continue because continue only makes sense with iteration constructs.