Break for loop from inside of switch case in Javascript

BASILIO picture BASILIO · Jun 12, 2013 · Viewed 28.3k times · Source

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

Answer

Brad Christie picture Brad Christie · Jun 12, 2013

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