0

Looking at the following Switch statement, if my value is 3 (I have made sure the type of value is a number by using parseInt(value, 10) so that's not the problem - also console.log(typeof value) would result in 'number') the 'name' variable should be set to 'three'. it's not the case though, and the switch statement directly goes to default. to make sure that the logic is correct, I changed the value to '1' and the 'name' variable got set to 'one'. why doesn't this work for value '3'? It's blown my mind!

               switch (value) {
                 case 0:
                    name = "zero";
                    break;
                 case (value & 1 == 1):
                    name = "one";
                    break;
                 case (value & 2 == 2):
                    name = "two";
                    break;
                 case (value & 3 == 3):
                    name = "three";
                    break;
                 default:
                 break;
               }

any ideas?

brainoverflow
  • 691
  • 2
  • 9
  • 22
  • You should put the value, not an expression, so case 3: – Lk77 Jul 08 '22 at 14:05
  • 1
    I think the issue is not related to the Bitwise Operators at all. The value that you pass in is tested against each case, and if it is the same, the code is executed. If you want to use expressions, you need to pass in `true`. So you would need to replace `value` with `true`, and in the first case, replace `0` with `value === 0`, and It should work. – HerrAlvé Jul 08 '22 at 14:07
  • 2
    3 & 1 still evaluates to 1, and you’re breaking from that case – skara9 Jul 08 '22 at 14:09
  • And also 3&2 == 2, but as @skara9 notes you don't even get that far. – President James K. Polk Jul 08 '22 at 14:10

0 Answers0