0

How can I set multiple conditions for switch statement in JS?

or How to set or condition inside switch?

eg:

switch(apple.amount) or switch(orange.amount)
{

case '1 kg':
total = 100;
break;

case '2 kg':
 total = 200;
break;
}
4
  • 1
    And exactly how would this work if both have values? Commented Mar 19, 2014 at 9:23
  • Encapsulate your switch in a function and pass both amounts to said function. Commented Mar 19, 2014 at 9:23
  • Either one have value at a time. Commented Mar 19, 2014 at 9:27
  • 2
    Do you mean switch(apple.amount || orange.amount)? Commented Mar 19, 2014 at 9:32

2 Answers 2

2

Use a loop:

var amounts = [apple.amount, orange.amount];
var totals = [];
for(var i = 0; i < amounts.length; i++){
    switch(amounts[i])
    {
        case '1 kg':
        totals[i] = 100;
        break;

        case '2 kg':
        totals[i] = 200;
        break;
    }
}

If your certain that only one will have a value during any execution you can use the || operator:

var amount1;
var amount2 = '2 kg';
var total;

    switch(amount1 || amount2 )
    {
        case '1 kg':
        total = 100;
        break;

        case '2 kg':
        total = 200;
        break;
    }

alert(total);
Sign up to request clarification or add additional context in comments.

Comments

0

Put the switch in a function and test the return value:

function getTotal(amount) {
  switch(amount) {
    case '1 kg':
      return 100
    case '2 kg':
      return 200
  }
}
if(getTotal(apple.amount) || getTotal(orange.amount)) {
    // both returns a total
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.