56

I'm doing a switch statement in javascript:

switch($tp_type){

    case 'ITP':
    $('#indv_tp_id').val(data);
    break;

     case 'CRP'||'COO'||'FOU':
    $('#jurd_tp_id').val(data);
    break;

}

But I think it doesn't work if I use OR operator. How do I properly do this in javascript? If I choose ITP,I get ITP. But if I choose either COO, FOU OR CRP I always get the first one which is CRP. Please help, thanks!

Wern Ancheta
  • 22,397
  • 38
  • 100
  • 139
  • 3
    See also [JavaScript or-expression in a switch case](http://stackoverflow.com/questions/6513585/javascript-or-expression-in-a-switch-case). – Brad Koch Mar 13 '13 at 17:45

1 Answers1

152

You should re-write it like this:

case 'CRP':
case 'COO':
case 'FOU':
  $('#jurd_tp_id').val(data);
  break;

You can see it documented in the switch reference. The behavior of consecutive case statements without breaks in between (called "fall-through") is described there:

The optional break statement associated with each case label ensures that the program breaks out of switch once the matched statement is executed and continues execution at the statement following switch. If break is omitted, the program continues execution at the next statement in the switch statement.

As for why your version only works for the first item (CRP), it's simply because the expression 'CRP'||'COO'||'FOU' evaluates to 'CRP' (since non-empty strings evaluate to true in Boolean context). So that case statement is equivalent to just case 'CRP': once evaluated.

Mat
  • 202,337
  • 40
  • 393
  • 406
  • 8
    This is called "fall-through": http://en.wikipedia.org/wiki/Switch_case . Putting each `case` on a separate line makes it easier to read IMO. – Felix Kling Jun 25 '11 at 09:33
  • 1
    is it possible to use calculations in a switch statement? for example, something like `case (expr / 2 < 10):` ?? – oldboy Jan 16 '20 at 20:45
  • @oldboy Switch statements aren't supposed to be this complex. Just use `if` statements at that point. – mrmicrowaveoven Dec 21 '21 at 17:58