var num = 0;
for(var i = 0; i < 10; i++){
for(var j = 0; j < 10 ; j++){
if(i == 5 && j == 5){
break;
}
num++;
}
}
console.log(num)
In the above code, I expect the result to be 55 but why the result is 95.
But why if I added the label, the result become 55?
var num = 0;
outermost:
for(var i = 0; i < 10; i++){
for(var j = 0; j < 10 ; j++){
if(i == 5 && j == 5){
break outermost;
}
num++;
}
}
console.log(num);
when used without label, break only break the current loop, in your case the innermost for. So now j = 6, the condition is now wrong, and the loops continues for 40 more incrementation.
When you put a label, break go to the "level" of the label, so the two for loops are skipped.
The first one is only breaking your "j" loop. After it breaks it, it returns to your "i" loop, and increments "i" to 6. Once "i" is 6, it returns to the "j" loop and the if condition is no longer met. So it continues to add up "num".
Using
break
without a label breaks the innermost loop which is currently executing.Using
break
with a labelfoo
breaks the statement labeledfoo
.MDN
break
docs:Without a label,
break
will break out of the inner loop. With a label you can stop execution of nested loops.See the examples:
https://developer.mozilla.org/en/JavaScript/Reference/Statements/label
when you use break without label , it only breaks the inner loop that is (i=5 j=6) ,(i=5 j=7) ,(i=5 j=8) ,(i=5 j=9) only and loop again starts with (i=6 j=0) to (i=9 j=9) and also count (num ++) startsthats why it show result as 95.
bt when you use break with label i.e. break outermost , it breaks out from the loop label as outermost (i.e the outer loop), thats why6 it gives output as 55
the break is given in only inner for loop. so it breaks only inner for loop when i = j = 5. but the outer loop continues to revolve 10 times. so when i=j=5 the loop will revolve only 5 times and in rest of all cases it will revolve 10 times.