0

If you use the break statement will it break all if...else...if else statements and all loops? If so how can you break just a single if/loop.

while(test here){if({break;}don't break;)}
Aurange
  • 943
  • 2
  • 9
  • 23

4 Answers4

4

The break statement will only break out of the one loop in that you put it in. It doesn't affect if/else statements. If you want to break an outer loop you can use labels, as in this answer.

while(true){
    if(something) {
        break;
        console.log("this won't ever be executed");
    } else {
        console.log("still in loop");
    }
}
Community
  • 1
  • 1
kapex
  • 28,903
  • 6
  • 107
  • 121
2

The break statement will break the loop and continue executing the code that follows after the loop (if any).

Check: http://www.w3schools.com/js/js_break.asp

Sudhir Bastakoti
  • 99,167
  • 15
  • 158
  • 162
2

break; will jump to the end of the deepest containing for, do, while or switch statement.

break label; will jump to the end of the labelled one.

if doesn't matter.

It's an error to break to a non-existant label, or if the relevant for, do, while, or switch is in a different function body.

Mike Samuel
  • 118,113
  • 30
  • 216
  • 245
1

I don't think there is a break for if statements. You'll have to restructure your if statement to only execute the code you need.

There is, however, a continue; which skips to the next iteration of the loop, while break; quits the loop entirely.

Steven Jackson
  • 424
  • 3
  • 8