Break for loop from inside of switch case in Javascript
Asked Answered
S

9

37

What command I must use, to get out of the for loop, also from //code inside jump direct to //code after

//code before
for(var a in b)
    {
    switch(something)
        {
        case something:
            {
            //code inside
            break;
            }
        }
    }
//code after
Sagittate answered 12/6, 2013 at 18:23 Comment(5)
Add break; right after the closing } of the switch statement.Osmond
you might consider refactoring your solution.Onshore
@Jaak Kütt Never touch my Indent style.Sagittate
@Sagittate don't draw attention with "i"-s and "sue"-s :).. would you atleast concider adding extra indent to the most inner comment and break?Moskva
@Jaak Kütt Ещё раз и по русский пожалуйста.Sagittate
J
18

Unfortunately, Javascript doesn't have allow breaking through multiple levels. The easiest way to do this is to leverage the power of the return statement by creating an anonymous function:

//code before
(function () {
    for (var a in b) {
        switch (something) {
        case something:
            {
                //code inside
                return;
            }
        }
    }
}());
//code after

This works because return leaves the function and therefore implicitly leaves the loop, moving you straight to code after


As pointed out in the comments, my above answer is incorrect and it is possible to multi-level breaking, as in Chubby Boy's answer, which I have upvoted.

Whether this is wise is, from a seven-year-later perspective, somewhat questionable.

Jibber answered 12/6, 2013 at 18:29 Comment(6)
I feel like an anonymous function is overkill for this kind of thing. Also, depending on how elaborate the for/switch can be, I might skim over the code and see a return and not associate it with the anonymous function (making maintenance a little more confusing later). Now, granted, this is not a complex piece of code, but applying this in practice throughout could become ugly fast.Franck
@BradChristie I'm not sure anonymous functions are so much of a big deal as to be overkill! As to the readability thing, that's what comments are for, surely... Refactoring would probably be the ideal, but this is the cleanest way to leave the loop.Jibber
Not dramatic, but i still see a difference.Franck
@BradChristie Personally, when we're talking on the scale of 13,000,000 ops/sec, I'm not too worried!Jibber
Untrue. Labels can be broken to. var b = 1; mySwitchLabel: switch(b) { case 1: for (var i=0; i<4; i++) { if (i === 0) { console.log('Break from Loop.') break mySwitchLabel; } } console.log('End of Case.') break; }Zoe
@LiamMitchell Many thanks: you are, of course, correct. My answer has been edited to point to the correct one elsewhere on this page.Jibber
F
42

You can use label. Have a labeled statement and break to that label. outerLoop is the label I have used here.

//code before
outerLoop:
for (var a in b) {
    switch (something) {
        case 'case1':
            //code inside
            break outerLoop;
    }
}
//code after
Fotinas answered 12/6, 2013 at 18:27 Comment(2)
It's okay to use label once, but that might end up with a spaghetti code if you use it more often. In this situations I'd first recommend to refactor the solution instead.Onshore
yay! spaghetti!Signore
F
28

use another variable to flag when you need to exit:

var b = { firstName: 'Peter', lastName: 'Smith' };
var keepGoing = true;
for (var a in b) {
  switch (true) {
    case 1:
      keepGoing = false;
      break;
  }
  if (!keepGoing) break;
  console.log('switch end');
}
console.log('for end');

example

Franck answered 12/6, 2013 at 18:25 Comment(1)
@downvoter: what gives? Perfectly acceptable (and although break permits a label parameter, I personally think labels went out with BASIC and just lead to spaghetti code...)Franck
J
18

Unfortunately, Javascript doesn't have allow breaking through multiple levels. The easiest way to do this is to leverage the power of the return statement by creating an anonymous function:

//code before
(function () {
    for (var a in b) {
        switch (something) {
        case something:
            {
                //code inside
                return;
            }
        }
    }
}());
//code after

This works because return leaves the function and therefore implicitly leaves the loop, moving you straight to code after


As pointed out in the comments, my above answer is incorrect and it is possible to multi-level breaking, as in Chubby Boy's answer, which I have upvoted.

Whether this is wise is, from a seven-year-later perspective, somewhat questionable.

Jibber answered 12/6, 2013 at 18:29 Comment(6)
I feel like an anonymous function is overkill for this kind of thing. Also, depending on how elaborate the for/switch can be, I might skim over the code and see a return and not associate it with the anonymous function (making maintenance a little more confusing later). Now, granted, this is not a complex piece of code, but applying this in practice throughout could become ugly fast.Franck
@BradChristie I'm not sure anonymous functions are so much of a big deal as to be overkill! As to the readability thing, that's what comments are for, surely... Refactoring would probably be the ideal, but this is the cleanest way to leave the loop.Jibber
Not dramatic, but i still see a difference.Franck
@BradChristie Personally, when we're talking on the scale of 13,000,000 ops/sec, I'm not too worried!Jibber
Untrue. Labels can be broken to. var b = 1; mySwitchLabel: switch(b) { case 1: for (var i=0; i<4; i++) { if (i === 0) { console.log('Break from Loop.') break mySwitchLabel; } } console.log('End of Case.') break; }Zoe
@LiamMitchell Many thanks: you are, of course, correct. My answer has been edited to point to the correct one elsewhere on this page.Jibber
T
9

it depends on what you want to accomplish... one thing I commonly do is something like this:

    //code before
for(var a in b)
{
    var breakFor = false;
    switch(something)
    {
        case something:
        {
            //code inside
            breakFor = true;
            break;
        }
    }
    if (breakFor)
        break;
}
//code after
Tyra answered 12/6, 2013 at 18:26 Comment(1)
Jeff was the first that use a bool var to accomplish this and other user takes more upvotes using the same statement. Why?Kneel
B
3

You can tell which loop / switch to break.

function foo ()
{
    dance:
    for(var k = 0; k < 4; k++){
        for(var m = 0; m < 4; m++){
            if(m == 2){
                break dance;
            }
        }
    }
}

See this answer.

Babyblueeyes answered 12/6, 2013 at 18:29 Comment(0)
C
2

Replace your switch with a series of if statements.

for (const a of b) {
  if (something === someValue) {
    // code inside
    break; // break out of the for loop
  } else if (something === someOtherValue) {
    // etc.
  }
}
Conscience answered 30/9, 2021 at 8:53 Comment(0)
S
1
for(var i=0; i<b.length; i++) {
   switch (something) {
       case 'something1':
           i=b.length;
   }
}

When the iteration variable i reaches the end of the loop, it breaks. But one can force the iteration variable to reach the end of the loop.

Stoughton answered 4/3, 2017 at 15:44 Comment(3)
It's better to include some explanation for this code, especially since there are six other answers.Benzoate
This does not solve the problem because the code will run 1 more time when i=b.length. Moreover, it's very dangerous if i is set lower than b.length, that will run forever!!!. So I recommend we should use function, label or flag instead of this.Whalen
@TrungLeNguyenNhat: the for loop condition looks for b < length, not <=, so once you set i = b.length, the condition will fail. The loop will not run one more time. In fact, even if you change it to i = b.length - 1, it will still break after this loop, because the incrementor runs before the condition.Anet
C
0

I always find using conditional statements one of the easiest ways to control the code flow, at least conceptually.

var done = false;
//code before for loop
for(var a in b){
    switch(switchParameter){
        case firstCase:
            //code inside
            done = true;
            break;
        }
    }
    if(done)
        break;
}
//code outside of for loop
Cruzeiro answered 12/6, 2013 at 18:29 Comment(0)
T
0
    const array = [1, 2, 3, 4, 5];

outerLoop: for (let i = 0; i < array.length; i++) {
  switch (array[i]) {
    case 1:
      console.log('Case 1');
      break; // This breaks out of the switch statement
    case 2:
      console.log('Case 2');
      break; // This breaks out of the switch statement
    case 3:
      console.log('Case 3');
      break outerLoop; // This breaks out of both the switch and the for loop
    default:
      console.log('Default case');
  }
}

console.log('Loop exited');
Tarsus answered 23/5 at 21:23 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.