[javascript] How to break nested loops in JavaScript?

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?

This question is related to javascript nested-loops break

The answer is


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();

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

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

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.


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

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();

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 Best way to break from nested loops in Javascript?

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


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


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


Use function for multilevel loops - this is good way:

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

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:


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.


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

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

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to nested-loops

Single Line Nested For Loops How to break out of nested loops? Breaking/exit nested for in vb.net bash shell nested for loop Iterate Multi-Dimensional Array with Nested Foreach Statement How to break nested loops in JavaScript? Can I use break to exit multiple nested 'for' loops? How do I break out of nested loops in Java? Breaking out of nested loops Breaking out of a nested loop

Examples related to break

How to break a while loop from an if condition inside the while loop? illegal use of break statement; javascript How can I use break or continue within for loop in Twig template? break statement in "if else" - java Regarding Java switch statements - using return and omitting breaks in each case Is it bad practice to use break to exit a loop in Java? break/exit script Breaking out of a for loop in Java How to break out of while loop in Python? How to kill a while loop with a keystroke?