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
It is not necessarily an antipattern to use a switch statement within a loop—it is only considered incorrect when used to model a known sequence of steps. The most common example of the correct use of a switch within a loop is an inversion of control such as an event handler.
You use the break statement to terminate a loop early such as the while loop or the for loop. If there are nested loops, the break statement will terminate the innermost loop. You can also use the break statement to terminate a switch statement or a labeled statement.
To come out of a switch case, use the break statement. The break statements indicate the end of a particular case.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With