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.
Using break
without a label breaks the innermost loop which is currently executing.
Using break
with a label foo
breaks the statement labeled foo
.
MDN break
docs:
The
break
statement includes an optional label that allows the program to break out of a labeled statement. Thebreak
statement needs to be nested within this labelled statement. The labelled statement can be any block statement; it does not have to be preceded by a loop statement.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With