Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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);
like image 522
dramasea Avatar asked Feb 25 '11 15:02

dramasea


2 Answers

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.

like image 193
krtek Avatar answered Sep 17 '22 15:09

krtek


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. The break 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.

like image 26
Matt Ball Avatar answered Sep 17 '22 15:09

Matt Ball