user1000131
user1000131

Reputation:

How are labels used with statements that are not a loop?

According to the ECMAScript 5.1 spec, section 12.12, any statement can be labelled - and in a brief test my browser accepted a label before any statement. The spec also states that labels are used exclusively with break and continue statements, and a quick test revealed that those statements throw an "undefined label" error if the label they reference does not refer to a loop that contains them.

So my question is this: what are labels for statements that are not loops used for? Is there some context in which break or continue can reference a label that is not a loop?

Upvotes: 8

Views: 477

Answers (2)

Varun Jain
Varun Jain

Reputation: 91

Yes you can label any statement. You just need to put the statement in curly braces, i.e.

{start:var a=1;}

this will not show undefined label error.

Upvotes: 0

Jeff
Jeff

Reputation: 12785

Apparently the break and continue statements can be used within any statement:

http://docstore.mik.ua/orelly/webprog/jscript/ch06_11.htm

In which case things like this become legal:

function show_alert()
{
    label:
    {
        break label;
        alert("Hello! I am an alert box!");
    }
    alert("hi");
}

When show_alert() is called, only the "hi" alert is shown.

As far as I know, this is the only use of the {} code blocks, other than for code styling. (there was a question on here about that, and noone could come up with anything other than readability, but I can't find it now...)

Upvotes: 5

Related Questions