3

I am having the understanding that break statement terminates all nested loops. I have written the following code and it is not working as expected.

<script>
    for (i = 0; i < 5; i++) {
        for (j = 0; j < 5; j++) {
            if (i == 3) {
                break;
            }
            document.write(i + '*' + j + '<br>');
        }
    }
</script>

Actual Output:

0*0
0*1
0*2
0*3
0*4
1*0
1*1
1*2
1*3
1*4
2*0
2*1
2*2
2*3
2*4
4*0
4*1
4*2
4*3
4*4

As per my understanding, the output should not include 4*0...4*4 because when i == 3, the break should terminate all nested loops.

Expected Output:

0*0
0*1
0*2
0*3
0*4
1*0
1*1
1*2
1*3
1*4
2*0
2*1
2*2
2*3
2*4
2
  • 1
    break terminates only the loop within which it is written Commented Mar 31, 2020 at 19:51
  • It terminates in the loop it is in, it is not terminating the outerloop. Working as expected. If you moved it before the for (j...., you would get what you were expecting. Commented Mar 31, 2020 at 19:51

4 Answers 4

10

You have to specify which loop you are breaking from.

loop1: for (i = 0; i < 5; i++) {
    loop2: for (j = 0; j < 5; j++) {
        if (i == 3) {
            break loop1;
        }
        document.write(i + '*' + j + '<br>');
    }
}

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/break

Sign up to request clarification or add additional context in comments.

1 Comment

OH this is the best solution than many spaghetti code comment
1

Why don't you place a break in the first loop?

<script>
  for (i = 0; i < 5; i++) {
    if (i == 3) break;
    for (j = 0; j < 5; j++) {
      document.write(i + '*' + j + '<br>');
    }
  }
</script>

Comments

0

No, break only breaks the current loop, not all of them. You can use a boolean variable to break out of the enclosing loop as well.

Example:

<script>
    let break = false
    for (i = 0; i < 5; i++) {
        for (j = 0; j < 5; j++) {
            if (i == 3) {
                break = true;
                break;
            }
            document.write(i + '*' + j + '<br>');
        }
        if(break) break
    }
</script>

Comments

0

By default the only innermost loop is escaped but you can achieve the behaviour you are expecting by a self enclosing function and a return statement.

(function(){
    for (i = 0; i < 5; i++) {
        for (j = 0; j < 5; j++) {
            if (i == 3) {
                return;
            }
            document.write(i + '*' + j + '<br>');
        }
    }
})()

Comments

Your Answer

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.