-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.

6
  • 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. Commented Aug 25, 2013 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: Commented Aug 25, 2013 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. Commented Aug 25, 2013 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. Commented Aug 25, 2013 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. Commented Aug 25, 2013 at 21:44

1 Answer 1

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];
           ...
       }
    }
Sign up to request clarification or add additional context in comments.

1 Comment

Or better yet, you fix your logic so you don't have to do that. But yes, that's how you do it.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.