dramasea
dramasea

Reputation: 3490

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

Upvotes: 20

Views: 17875

Answers (6)

Matt Ball
Matt Ball

Reputation: 359826

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.

Upvotes: 5

Harish Singh Bisht
Harish Singh Bisht

Reputation: 121

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

Upvotes: 1

Jay Dave
Jay Dave

Reputation: 11

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.

Upvotes: 1

RussellUresti
RussellUresti

Reputation: 6221

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".

Upvotes: 1

davin
davin

Reputation: 45525

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

Upvotes: 4

krtek
krtek

Reputation: 26597

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.

Upvotes: 22

Related Questions