1

Java Switch Statement - Is "or"/"and" possible?

There are quite a few answers like the above that give good alternatives to using this erroneous syntax in my example but I haven't read an explanation to why it doesn't work:

const switchExample = (val) => {
    switch(val) {
        case 'a' || 'b' || 'c':
        return 'first 3'
        break;
        case 'd':
        return 'fourth'
        break;
        default:
        return 'default'
    }
}

Invoking with 'b' or 'c' as a param will return the default. Whereas 'a' will return (as expected) 'first 3'. I was expecting that if 'b' was truthy, then the first case would evaluate to true and return 'first 3' but this ins't the case. Can somebody explain why?

BBrow
  • 79
  • 7
  • Because that's not the syntax of the language to combine cases? Or do you want the technical details about what happens? – Some programmer dude Apr 30 '20 at 08:09
  • 2
    `('a' || 'b' || 'c') === 'a'` (there are a few questions on SO that cover this, e.g. https://stackoverflow.com/questions/2966430/why-does-javascripts-or-return-a-value-other-than-true-false). The `switch` is treating all of the `case` expressions the same: as values to compare against. – Ry- Apr 30 '20 at 08:10
  • Thanks - no need for technical details - ('a' || 'b' || 'c') === 'a' clears this up for me - I need to read up on logic rather than the switch statements per se. – BBrow Apr 30 '20 at 08:38

2 Answers2

0

It does not work, because the first truthy value is taken by using logical OR || for a strict comparison.

Alternatively, you could use a fall through approach with having three cases in a line, like

const
    switchExample = (val) => {
        switch(val) {
            case 'a':
            case 'b':
            case 'c':
                return 'first 3'; // no break required, because return ends the function
            case 'd':
                return 'fourth';
            default:
                return 'default';
        }
    }
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
0

Here

    switch(val) {
        case 'a' || 'b' || 'c':

the value of the expression 'a' || 'b' || 'c' will be first evaluated (it's 'a'), and then the switch will examine whether val fits the case.

You need to do the alternative this way:

    switch(val) {
        case 'a':
        case 'b':
        case 'c':
            return 'first 3';
        case 'd':
// ...
mbojko
  • 13,503
  • 1
  • 16
  • 26