How to break nested loops in JavaScript?

Mask picture Mask · Oct 14, 2009 · Viewed 117.1k times · Source

I tried this:

for(i = 0; i < 5; i++){
    for(j = i + 1; j < 5; j++){
        break(2);
    }
    alert(1);
}

only to get:

SyntaxError: missing ; before statement

So, how would I break a nested loop in JavaScript?

Answer

Noon Silk picture Noon Silk · Oct 14, 2009

You should be able to break to a label, like so:

function foo ()
{
    dance:
    for(var k = 0; k < 4; k++){
        for(var m = 0; m < 4; m++){
            if(m == 2){
                break dance;
            }
        }
    }
}