Search code examples
javascriptif-statementecmascript-6language-lawyerlabeled-statements

Is it a browser bug that I can't use js labeled statements with an if?


Disclaimer: Yes, I know goto is bad, I'm interested here in the spec and implementations, not best practices.

I have this super simple javascript example of a labeled statement

let i = 0;
foo:
if(i < 5) {
    console.log(i);
    i +=1;
    continue foo;
}

As far as I can tell for the spec for labelled statements and for statements this should work!

So am I reading the spec wrong or is there a bug somewhere?

Note that usage as shown on MDN with for statements works fine


Solution

  • From the specification for continue:

    It is a Syntax Error if this production is not nested, directly or indirectly (but not crossing function boundaries), within an IterationStatement.

    An IterationStatement is defined as a for loop or a case block. An if block is an IfStatement, not an IterationStatement, so you cannot use continue inside one.