0

I have a for loop and inside that for loop I have another for loop with a condition for break. The problem is that when the sub for loop breaks the top-level loop also does it. So how do I a break a sub for loop without breaking the main for loop in javascript?

BoltClock
729k165 gold badges1.4k silver badges1.4k bronze badges
asked Nov 9, 2011 at 7:30
1
  • 7
    Javascript doesn't cause outer loops to break when inner loops breaks. If your code is doing this then something else is going on. Commented Nov 9, 2011 at 7:49

1 Answer 1

1

Use a break statement, thus:

var i, j, s = "";
for(i = 0; i < 5; ++i) {
 s += "\ni = " + i;
 for(j = 0; j < 999; ++j) {
 s += "\nj = " + j;
 if(j === 1) {
 break;
 }
 } 
}

Notice that at the end, s contains the result of five iterations of the whole loop, rather than one.

One possible cause for your issue might be an extra misplaced semicolon, thus:

var i, j, s;
s = "";
for(i = 0; i < 5; ++i) {
 s += "\ni = " + i;
 for(j = 0; j < 10; ++j); {
 s += "\nj = " + j;
 if(j === 10) {
 break;
 }
 } 
}

In the above case, the inner for loop is actually empty, but indentation makes it look as though it contains the following block (which is actually an immediate child of the "outer" loop). This means that the apparent "outer" loop will break on the first iteration.

Another cause might be a typo leading to the incorrect use of assignment vs equality, thus:

var i, j, s;
s = "";
for(i = 0; i < 5; ++i) {
 s += "\ni = " + i;
 for(j = 0; j < 10; ++j) {
 s += "\nj = " + j;
 if(i = 5) {
 break;
 }
 } 
}

In this situation, in the condition that causes the inner loop to break, the loop variable of the outer loop has been assigned a value that causes the outer loop to finish. Assignment is truthy, so the break will always be hit.

Yet another cause might be a misunderstanding about variable scope in javascript. In other languages, you might be able to do something like this:

var i, s = "";
for(i = 0; i < 5; ++i) {
 s += "\nouter = " + i;
 if(true) {
 var i;
 for(i = 0; i < 999; ++i) {
 s += "\ninner = " + i;
 if(i === 10) {
 break;
 }
 }
 } 
}

The trouble here is that in javascript, variables are scoped to the function in which they are declared with var. (or global, if outside a function or used without var). This means that the i of the inner loop is actually the same i as the outer loop

answered Nov 9, 2011 at 8:27
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.