Break for loop from inside of switch case in Javascript
Unfortunately, Javascript doesn't have allow break
ing 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 break
ing, as in Chubby Boy's answer, which I have upvoted.
Whether this is wise is, from a seven-year-later perspective, somewhat questionable.
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
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
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