Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
130
rated 0 times [  133] [ 3]  / answers: 1 / hits: 16560  / 14 Years ago, fri, february 25, 2011, 12:00:00



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);




More From » label

 Answers
26

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.


[#93578] Wednesday, February 23, 2011, 14 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
loganl

Total Points: 424
Total Questions: 86
Total Answers: 112

Location: Zimbabwe
Member since Thu, Jul 21, 2022
2 Years ago
;