What command I must use, to get out of the for loop, also from //code inside
jump direct to //code after
JavaScript
x
14
14
1
//code before
2
for(var a in b)
3
{
4
switch(something)
5
{
6
case something:
7
{
8
//code inside
9
break;
10
}
11
}
12
}
13
//code after
14
Advertisement
Answer
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:
JavaScript
1
14
14
1
//code before
2
(function () {
3
for (var a in b) {
4
switch (something) {
5
case something:
6
{
7
//code inside
8
return;
9
}
10
}
11
}
12
}());
13
//code after
14
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.