Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 
like image 277
BASILIO Avatar asked Jun 12 '13 18:06

BASILIO


People also ask

Can I use switch case inside for loop?

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.

Can you break from a for loop JavaScript?

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.

How do you break out of a switch in JavaScript?

To come out of a switch case, use the break statement. The break statements indicate the end of a particular case.


2 Answers

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 
like image 131
Chubby Boy Avatar answered Oct 07 '22 19:10

Chubby Boy


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

like image 35
Brad Christie Avatar answered Oct 07 '22 18:10

Brad Christie