Search code examples
javascriptlabeled-statements

labeled statement - incorrect definition?


For JavaScript's label syntax, JS MDN states:

label : statement

label: Any JavaScript identifier that is not a reserved word.

statement: A JavaScript statement.

break can be used with any labeled statement, and continue can be used with looping labeled statements.

According to that, you can break as follows:

statement: {
  console.log("this will log");
  break statement;
  console.log("this will not log");
}

And, since it says that you can break any labeled statements, I would've expected this to work:

function func() {
  console.log("works?")
  break statement;
  console.log("this too?")

}

statement: {
  console.log("this will log");
  func();
  console.log("this will not log");
}
// throws Uncaught SyntaxError: Undefined label 'statement'

But it throws Uncaught SyntaxError: Undefined label 'statement'

I thought maybe I can update the func as follows:

function func(breakMe) {
  console.log("works?")
  break breakMe;
  console.log("this too?")

}

statement: {
  console.log("this will log");
  func(statement);
  console.log("this will not log");
}

// throwsUncaught SyntaxError: Undefined label 'statement'

But statement cannot be referenced that way (throwing statement is not defined);

Same error here:

    statement: {
      function func() {
        console.log("works?")
        break statement;
        console.log("this too?")
      }
      console.log("this will log");
      func();
      console.log("this will not log");
    }

It seems I have a fundamental misunderstanding as to what exactly is this "any" referring to.

Given that this works:

labelOne: {
  console.log("this will log")
  labelTwo: {
    console.log("will log too");
    break labelOne;
    console.log("this won't log");
  }
  console.log("neither will this");
}

maybe a more accurate description would be:

break can only be used with labeled statement in the context of those statements.

But even so, with this description, func() should've broken the execution of the statement labeled statement, since it was in the same context from my POV.

So is the syntax incorrectly/incompletely defined or am I missing something?


Solution

  • The break must be literally nested inside the label. It's perfectly possible to call func from outside a labelled context, so break wouldn't refer to anything. The same goes for break and continue in reference to loops, they must be literally within the loop statement.

    Put another way, a function must be a self-contained executable snippet. You must be able to look at a function and be able to tell what it does. break in that function doesn't obviously belong to any loop or label, it's nonsensical there. That meaning can't just be available at call-time, it must be available at time of declaration.