-2

I have 2 nested loops that look like this:

for (var i = 0; i < SomeArray.length; i++) {

   for (var prop in SomeArray[i]) {

      if (SomeCondition) {

          break; // here I need to break from the outer for-loop
      }
   }
}

The break statement exits the for-in loop from the object's property but I want to exit the outer for loop.

How do I do that? I thought of setting the value of i to be equal to the length of the outer loop's array but I'm wondering if there's a better way.

Thanks.

frenchie
  • 51,731
  • 109
  • 304
  • 510
  • 1
    This is a basic language concept. Guessing there was no search done first. You must have ignored suggested duplicates offered when editing the question. –  Aug 25 '13 at 21:06
  • 1
    @CrazyTrain: actually, if you ask a question and type "breaking from outer loop while looping through inner loop" there are no javascript duplicates that answer the question using label: – frenchie Aug 25 '13 at 21:11
  • @frenchie: Plenty of information to point one to a solution. You'll see many languages listed with a common feature. Then you google `javascript break statement`, and bingo. Or just skip right to google and search `javascript break outer loop`. Easy to find with absolute minimal effort. –  Aug 25 '13 at 21:15
  • @CrazyTrain: well now if someone googles "breaking from outer loop while looping through inner loop" they'll reach this page and I think that'll be helpful. – frenchie Aug 25 '13 at 21:35
  • You mean if someone puts forth a tiny bit of effort and actually tries to find the answer for themselves? Then yes, that industrious person will have the solution. Glad to see you're finally catching on. –  Aug 25 '13 at 21:44
  • @CrazyTrain: I did google "breaking from outer loop while looping through inner loop" and nothing came up for javascript, that's why I asked the question. – frenchie Aug 25 '13 at 22:00

1 Answers1

3

You can do that by adding a label.

   outer: 
   for (var i = 0; i < SomeArray.length; i++) {

       for (var prop in SomeArray[i]) {

          if (SomeCondition) {

              break outer; // here I need to break from the outer for-loop
          }
       }
    }

That's the most direct answer to your question. But labels are frowned upon because because they're rarely used, not well known, and make the code hard to follow. It would be better to rewrite your code, e.g.

    for (var i = 0; i < SomeArray.length && !SomeCondition; i++) {

       for (var j = 0; j < SomeArray[i].length && !SomeCondition; j++) {
           var prop = SomeArray[i][j];
           ...
       }
    }
Patrick McElhaney
  • 57,901
  • 40
  • 134
  • 167