How to break nested loops in JavaScript?

JavascriptNested LoopsBreak

Javascript Problem Overview


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?

Javascript Solutions


Solution 1 - Javascript

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;
            }
        }
    }
}

Solution 2 - Javascript

You need to name your outer loop and break that loop, rather than your inner loop - like this.

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

Solution 3 - Javascript

There are at least five different ways to break out of two or more loops:

1) Set parent(s) loop to the end

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

2) Use label

fast:
for (i = 0; i < 5; i++)
{
    for (j = 0; j < 5; j++)
    {
        if (j === 2)
            break fast;
    }
}

3) Use variable

var exit_loops = false;
for (i = 0; i < 5; i++)
{
    for (j = 0; j < 5; j++)
    {
        if (j === 2)
        {
            exit_loops = true;
            break;
        }
    }
    if (exit_loops)
        break;
}

4) Use self executing function

(function()
{
    for (i = 0; i < 5; i++)
    {
        for (j = 0; j < 5; j++)
        {
             if (j === 2)
                 return;
        }
    }
})();

5) Use regular function

function nested_loops()
{
    for (i = 0; i < 5; i++)
    {
        for (j = 0; j < 5; j++)
        {
             if (j === 2)
                 return;
        }
    }
}
nested_loops();

Solution 4 - Javascript

See Aaron's. Otherwise: j=5;i=5 instead of break.

Solution 5 - Javascript

loop1:
    for (var i in set1) {
loop2:
        for (var j in set2) {
loop3:
            for (var k in set3) {
                break loop2;  // breaks out of loop3 and loop2
            }
        }
    }

code copied from https://stackoverflow.com/questions/183161/best-way-to-break-from-nested-loops-in-javascript/183197#183197

Please search before posting a question. The link was the FIRST related question I saw on the left side of this page!

Solution 6 - Javascript

Unfortunately you'll have to set a flag or use labels (think old school goto statements)

var breakout = false;

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

The label approach looks like:

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

edit: label incorrectly placed.

also see:

Solution 7 - Javascript

In my opinion, it's important to keep your construct vocabulary to a minimum. If I can do away with breaks and continues easily, I do so.

function foo ()
{
    var found = false;
    for(var k = 0; (k < 4 && !found); k++){
        for(var m = 0; (m < 4 && !found); m++){
           if( m === 2){
               found = true;
           }
        }
    }
    return found;
}

Be warned, after the loop, m and k are one larger that you might think. This is because m++ and k++ are executed before their loop conditions. However, it's still better than 'dirty' breaks.

EDIT: long comment @Dennis...

I wasn't being 100% serious about being 'dirty', but I still think that 'break' contravenes my own conception of clean code. The thought of having multi-level breaks actually makes me feel like taking a shower.

I find justifying what I mean about a feeling about code because I have coded all life. The best why I can think of it is is a combination of manners and grammar. Breaks just aren't polite. Multi level breaks are just plain rude.

When looking at a for statement, a reader knows exactly where to look. Everything you need to know about the rules of engagement are in the contract, in between the parenthesis. As a reader, breaks insult me, it feels like I've been cheated upon.

Clarity is much more respectful than cheating.

Solution 8 - Javascript

Use function for multilevel loops - this is good way:

function find_dup () {
    for (;;) {
        for(;;) {
            if (done) return;
        }
    }
}

Solution 9 - Javascript

Wrap in a self executing function and return

(function(){
    for(i=0;i<5;i++){
        for (j=0;j<3;j++){
            //console.log(i+' '+j);
            if (j == 2) return;
        }
    }
})()

Solution 10 - Javascript

You return to "break" you nested for loop.

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

Solution 11 - Javascript

You can break nested for loops with the word 'break', it works without any labels.

In your case you need to have a condition which is sufficient to break a loop.

Here's an example:

var arr = [[1,3], [5,6], [9,10]];
for (var a = 0; a<arr.length; a++ ){
  for (var i=0; i<arr[a].length; i++) {
    console.log('I am a nested loop and i = ' + i);
    if (i==0) { break; }
  }
  console.log('first loop continues');
}

It logs the following:

> I am a nested loop and i = 0 
> first loop continues
> I am a nested loop and i = 0 
> first loop continues
> I am a nested loop and i = 0 
> first loop continues

The return; statement does not work in this case. Working pen

Solution 12 - Javascript

The another trick is by setting the parent loop to reach the end and then break the current loop

function foo()
{
    for(var k = 0; k < 4; k++){
        for(var m = 0; m < 4; m++){
            if(m == 2){
                k = 5; // Set this then break
                break;
            }
          console.log(m);
        }
    }
}

Solution 13 - Javascript

break doesn't take parameters. There are two workarounds:

  1. Wrap them in a function and call return

  2. Set a flag in the inner loop and break again right after the loop if the flag is set.

Solution 14 - Javascript

Break 1st loop:

for(i=0;i<5;i++)
{
  for(j=i+1;j<5;j++)
  {
    //do something

    break;
  }
  alert(1);
};

Break both loops:

for(i=0;i<5;i++)
{
  var breakagain = false;
  for(j=i+1;j<5;j++)
  {
    //do something

    breakagain = true;
    break;
  }
  alert(1);
  if(breakagain)
    break;
};

Solution 15 - Javascript

function myFunction(){
  for(var i = 0;i < n;i++){
    for(var m = 0;m < n;m++){
      if(/*break condition*/){
        goto out;
      }
    }
  }
out:
 //your out of the loop;
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMaskView Question on Stackoverflow
Solution 1 - JavascriptNoon SilkView Answer on Stackoverflow
Solution 2 - JavascriptFentonView Answer on Stackoverflow
Solution 3 - JavascriptDan BrayView Answer on Stackoverflow
Solution 4 - JavascriptGlennView Answer on Stackoverflow
Solution 5 - JavascriptJimView Answer on Stackoverflow
Solution 6 - JavascriptJonathan FinglandView Answer on Stackoverflow
Solution 7 - Javascriptthomas-peterView Answer on Stackoverflow
Solution 8 - JavascriptAnatoliyView Answer on Stackoverflow
Solution 9 - JavascriptkehersView Answer on Stackoverflow
Solution 10 - JavascriptGibboKView Answer on Stackoverflow
Solution 11 - JavascriptIlya KushlianskiView Answer on Stackoverflow
Solution 12 - JavascriptStefansAryaView Answer on Stackoverflow
Solution 13 - JavascriptAaron DigullaView Answer on Stackoverflow
Solution 14 - Javascripto.k.wView Answer on Stackoverflow
Solution 15 - JavascriptjunmatsView Answer on Stackoverflow