tags:

views:

83

answers:

2

I pulled up the NWmatcher source code for some light morning reading and noticed this odd bit of code I'd never seen in javascript before:

main:for(/*irrelevant loop stuff*/){/*...*/}

This snippet can be found in the compileGroup method on line 441 (nwmatcher-1.1.1)

return new Function('c,s,d,h',
    'var k,e,r,n,C,N,T,X=0,x=0;main:for(k=0,r=[];e=N=c[k];k++){' + 
         SKIP_COMMENTS + source + 
    '}return r;'
);

Now I figured out what main: is doing on my own. If you have a loop within a loop and want to skip to the next iteration of the outer loop (without completing the inner OR the outer loop) you can execute continue main. Example:

// This is obviously not the optimal way to find primes...
function getPrimes(max) {
    var primes = [2], //seed
        sqrt = Math.sqrt,
        i = 3, j, s;

    outer: for (; i <= max; s = sqrt(i += 2)) {
        j = 3;
        while (j <= s) {
            if (i % j === 0) {
                // if we get here j += 2 and primes.push(i) are
                // not executed for the current iteration of i
                continue outer;
            }
            j += 2;
        }
        primes.push(i);
    }
    return primes;
}

What is this called?
Are there any browsers that don't support it?
Are there other uses for it other than continue?

+4  A: 

This is labeled continue. You can also use labeled break. It's standard since ECMAScript 3. It works essentially the same way in Java.

Matthew Flaschen
+1  A: 

That is simply an example of using Labels to control flow. It is part of the standard and, as far as I know, all browsers support it.

As for other uses, check out exactly what you can do with it at (in addition to continue, labels can be used with break):

Tutorialspoint - JavaScript Loop Control with break and continue

Justin Niessner