George Mauer
George Mauer

Reputation: 122102

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

Upvotes: 0

Views: 50

Answers (2)

jmh
jmh

Reputation: 9336

The problem is that continue can only be used in a loop.

The continue statement terminates execution of the statements in the current iteration of the current or labeled loop, and continues execution of the loop with the next iteration.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/continue

Upvotes: 0

user149341
user149341

Reputation:

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.

Upvotes: 4

Related Questions