Skip to content
Advertisement

Break for loop from inside of switch case in Javascript

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

Advertisement

Answer

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.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement