Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does the logical OR operator in switch cases behave strangely?

Tags:

javascript

The testMyNumber function seems to think numbers in the second position do not match.

Why do 4 and 10 return the default case?

function testMyNumber(number) {
  switch (number) {
    case 6:
      return number+" is 6";
      break;
    case (3 || 4) :
      return number+" is 3 or 4";
      break;

    case 9 || 10 :
      return number+" is 9 or 10";
      break;

    default:
      return number+" is not in 3,4,6,9,10";
      break;
  }
};
console.log(testMyNumber(6));
console.log(testMyNumber(3));
console.log(testMyNumber(4));
console.log(testMyNumber(9));
console.log(testMyNumber(10));

Is there a way to make this work?

like image 417
Cem Kaan Avatar asked Jun 15 '20 09:06

Cem Kaan


People also ask

Can we use logical operators in switch cases?

The logical OR operator (||) will not work in a switch case as one might think, only the first argument will be considered at execution time.

Why do switch statements fall through?

Reports a switch statement where control can proceed from a branch to the next one. Such "fall-through" often indicates an error, for example, a missing break or return .

Can we use logical operators in switch statement in C#?

There is no such operator in switch statements. The switch statement operates on a single variable which is a value type or a string.


2 Answers

Because it wasn't intended to be used this way.

|| returns its first operand if it's truthy, else its second operand.

3 || 4 returns 3 because 3 is truthy, therefore case will check only 3:

console.log(3 || 4); //3, because it is truthy
console.log(0 || 1); //1, because 0 is falsy

To make your code work, use separate cases, that fall through:

function testMyNumber(number) {
  switch (number) {
    case 6:
      return number+" is 6";
    case 3:
    case 4:
      return number+" is 3 or 4";

    case 9:
    case 10:
      return number+" is 9 or 10";
    default:
      return number+" is not in 3,4,6,9,10";
  }
};
console.log(testMyNumber(6));
console.log(testMyNumber(3));
console.log(testMyNumber(4));
console.log(testMyNumber(9));
console.log(testMyNumber(10));
like image 176
FZs Avatar answered Sep 20 '22 09:09

FZs


Why 4 returns default case?

Because (3 || 4) is equal to 3, so case (3 || 4): is the same as writing case 3:.

You are using incorrect syntax. Write it like this:

case 3:
case 4:
    return number + " is 3 or 4";
like image 32
Jesper Avatar answered Sep 21 '22 09:09

Jesper