techq
techq

Reputation: 85

how to break multiple if statements in javascript

I want to break the execution when it matches particular condition. Have tried break,goto and did not work.Please advise.

if (condition 1){
   print("1");
}
if (condition 2){
   print("2");
}
if (condition 3){
   print("3");
} 

Thanks.

Upvotes: 0

Views: 660

Answers (2)

Alexander Nied
Alexander Nied

Reputation: 13623

I am highly confused by your assertion that switch and else...if do "not fit [your] use case"-- those are the constructs Javascript provides explicitly for the case you are seeking-- evaluating a series of conditions and breaking when one is matched. By this measure, Lahiru Ashan's answer is a valid one, and the comments on your question are also valid solutions.

The only other means I can think of, if for some bizarre reason you truly cannot use an if..else or a switch in your code, would be to place all the conditionals in a function, and use a return statement to short circuit and exit the function when you are complete. Something like this:

function evaluateInput(inputVal) {
    if (inputVal === 1){
       print("1");
       return;
    }
    if (inputVal === 2){
       print("2");
       return;
    }
    if (inputVal === 3){
       print("3");
       return;
    }
}

x = 3
evaluateInput(x);

However, I really think you need to revisit the other potential solutions, as they are valid and far more conventional means to achieve what you seek. The if..else solution is simple and straightforward:

    x = 3
    if (x === 1){
       print("1");
    } else if (x === 2){
       print("2");
    } else if (x === 3){
       print("3");
    } 

If you have a long chain of conditions to evaluate and this looks like too much overhead, then the switch statement is an excellent alternative, in which case Lahiru Ashan's solution is a valid contender.

It is my suspicion that the if..else or switch should be valid for your scenario-- if they are not, perhaps you should explain more clearly why they are not, with examples in code, to help the StackOverflow community evaluate your issue and help you arrive at a solution.

Upvotes: 2

Lahiru Ashan
Lahiru Ashan

Reputation: 767

try using switch,

var x = 3;

switch(x){
  case 1:{
   alert('one');
   break;
  }
 case 2:{
  alert('two');
  break;
 }
 case 3:{
  alert('three');
  break;
 }
 case 4:{
  alert('four');
  break;
 }
}

Upvotes: 0

Related Questions