unbindall
unbindall

Reputation: 514

Breaking out of a while loop and switch in one go

There is a similar question concerning this problem in C++, but I'm using JavaScript here. I'm basically in the same situation as the OP in the other post.

var input = prompt();
while(true) {
    switch(input) {
        case 'hi':
        break;
        case 'bye':
            //I want to break out of the switch and the loop here
        break;
    }
    /*Other code*/
}

Is there anyway to do that?

I also have multiple switches in the /*Other code*/ section where the code should also break.

Upvotes: 3

Views: 4045

Answers (4)

Calummm
Calummm

Reputation: 829

You can use labels with the break statement in js

var input = prompt();

outside:
while(true) {
    switch(input) {
        case 'hi':
        break;
        case 'bye':
            //I want to break out of the switch and the loop here
        break outside;
    }
    /*Other code*/
}

Upvotes: 6

Thought
Thought

Reputation: 700

It's the same answer as in C++, or most other languages. Basically, you just add a flag to tell your loop that it's done.

var input = prompt();
var keepGoing = true;
while(keepGoing) {
    switch(input) {
        case 'hi':
            break;
        case 'bye':
            //I want to break out of the switch and the loop here
            keepGoing = false;
            break;
    }
    // If you need to skip other code, then use this:
    if (!keepGoing)  break;
    /*Other code*/
}

Make sense?

Upvotes: 1

Etheryte
Etheryte

Reputation: 25319

Wrap the whole thing in a function, then you can simply return to break out of both.

var input = prompt();
(function () {
    while(true) {
        switch(input) {
            case 'hi':
            break;
            case 'bye':
            return;
        }
        /*Other code*/
    }
})();

Upvotes: 4

Paul Roub
Paul Roub

Reputation: 36438

Don't diminish readability in the name of "one less line of code". Make your intentions clear:

while (true) {
  var quit = false;

  switch(input) {
    case 'hi':
      break;

    case 'bye':
      quit = true;
      break;
  }

  if (quit)
    break;

  /*Other code*/
}

Upvotes: 0

Related Questions