what the difference between break with label and without label in javascript

dramasea picture dramasea · Feb 25, 2011 · Viewed 13.8k times · Source

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

Answer

krtek picture krtek · Feb 25, 2011

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.