Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using OR operator in javascript switch statement [duplicate]

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!

like image 745
Wern Ancheta Avatar asked Jun 25 '11 09:06

Wern Ancheta


People also ask

Can switch statement use double?

switch expression can't be float, double or boolean.

Can switch case have multiple conditions JavaScript?

The JavaScript switch case is a multiple if else statement. It takes a conditional expression just like an if statement but can have many conditions—or cases—that can match the result of the expression to run different blocks of code.

Can you do switch statements in JavaScript?

The switch statement is a part of JavaScript's "Conditional" Statements, which are used to perform different actions based on different conditions. Use switch to select one of many blocks of code to be executed. This is the perfect solution for long, nested if/else statements.

Can we use expression in switch case?

The expression in the switch can be a variable or an expression - but it must be an integer or a character. You can have any number of cases however there should not be any duplicates. Switch statements can also be nested within each other. The optional default case is executed when none of the cases above match.


1 Answers

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.

like image 120
Mat Avatar answered Sep 25 '22 23:09

Mat