3

My confusion stems from this example labelled statement:

myLoop : while (expression) {
    continue myLoop;
}

and the syntax of a general labelled statement:

identifier : statement

What exactly is being labelled in the example?

isn't the whole block of code:

while (expression) 
    statement

considered a single statement? Or is while(expression) itself a statement? Or is while a statement by itself?

Why isn't the entire:

while (expression) {
    continue myLoop;
} 

labelled under myLoop and not just while(expression). Or is that even happening?

JJJ
  • 32,902
  • 20
  • 89
  • 102
Fawkes5
  • 1,001
  • 3
  • 9
  • 12

2 Answers2

5

I'd never seen labelled while loops before, but according to this http://james.padolsey.com/javascript/looping-in-javascript/ it is the whole while loop that is being labelled.

The use for it is to break out of a particular loop, handy with loops-in-loops e.g. (example taken from the link)

myOuterLoop : while (condition) {
 myInnerLoop : while (condition) {
    if (whatever) {
        break myOuterLoop;
    }
    if (whatever2) {
        break; // Same as 'break myInnerLoop;'
    }
 }
}
Ben Clayton
  • 80,996
  • 26
  • 120
  • 129
2

What's being labelled isn't a block of code, it's just a particular line. So wherever your label myLoop is, writing continue myLoop is like saying "jump to that spot and continue execution".

But actually, in this example:

myLoop : while (expression) {
    continue myLoop;
}

The use of the label is completely redundant. You would write it as follows and the effect would be identical:

while (expression) {
    continue;
}

That's because continue by default means, go to the beginning of the loop's next iteration.

McGarnagle
  • 101,349
  • 31
  • 229
  • 260
  • Moreover, A loop (In this case `while`) is dealt like a single statement, even though it comprises of multiple statements in itself(Block of code). – Furqan Hameedi Jun 26 '12 at 07:45