Ali Khan Ali Khan - 24 days ago 7
Javascript Question

Why Switch statement only working with true keyword?

Can anyone explain to me why first one is not working and second one is working?

First Statement

function test(n) {
switch (n) {
case (n == 0 || n == 1):
console.log("Number is either 0 or 1");
break;
case (n >= 2):
console.log("Number is greater than 1")
break;
default:
console.log("Default");
}
}


Second Statement

function test(n) {
switch (true) {
case (n == 0 || n == 1):
console.log("Number is either 0 or 1");
break;
case (n >= 2):
console.log("Number is greater than 1")
break;
default:
console.log("Default");
}
}

Answer Source

The parameter which is given to the switch will be compared using ===. In cases which you have, you have expressions which result to boolean type: n==0 || n==1 or n >= 2. When you pass a number , it tries to compare your number with a result given from the expression in cases. So for example with the given number 1 it tries to compare 1 === (1 == 0 || 1 == 1) -> 1 === true which returns false (strict comparison). So you get the Default text every time.

For the first case, you need to have numbers in the cases of your switch , not a boolean (n==0 || n==1 results to boolean).

With the second case, you have in the switch value true of type boolean.When you pass again 1 the comparing goes like true === (1 == 0 || 1 == 1) -> true === true and it returns true. So you get the desired result according to your value n. But the second case has no goals with using true as the value. You can replace it with a if else if statement.

If you want to get the same result for many cases you need to write 2 cases above each other. See this

case 0:
case 1:
  result

Here the cases have type number, not boolean.

Code example.

function test(n){
    switch (n) {
    case 0:
    case 1:
    console.log("Number is either 0 or 1");
    break;
    case 2:
    console.log("Number is 2")
    break;
    default:
    console.log("Default");}
}

test(0);
test(1);
test(2)