Reputation: 15639
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>
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.
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
Upvotes: 3
Views: 3881
Reputation: 4536
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>
Upvotes: 1
Reputation: 1855
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>');
}
}
})()
Upvotes: 0
Reputation: 238
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
Upvotes: 10
Reputation:
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>
Upvotes: 0