Troskyvs
Troskyvs

Reputation: 8047

Javascript: weird syntax error when using "label"

This code piece

abc:
var i=0;
for (; i < 10; ++i)
    if (i == 8) break abc;

has runtime exception, saying

SyntaxError: Undefined label 'abc'

If I remove the line of

var i=0;

Then it's OK.

This is weird to me. Does javascript requires any label, if used by "break"/"continue", definition is only available to the code block right following it, or else it's not accessible? Thanks.

Upvotes: 0

Views: 538

Answers (2)

li0n_za
li0n_za

Reputation: 455

Your label needs to be directly before the loop:

var i=0;
abc:
for (; i < 10; ++i)
    if (i == 8) break abc;

Upvotes: 0

Quentin
Quentin

Reputation: 943569

From MDN:

The break statement needs to be nested within the referenced label.

So, yes.

Upvotes: 2

Related Questions