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");
    }
}

Answers:

Answer

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)

Answer

switch uses strict comparison.

You take a number in the switch statement and in cases, just comparsions which return a boolean value.

A switch statement first evaluates its expression. It then looks for the first case clause whose expression evaluates to the same value as the result of the input expression (using strict comparison, ===) and transfers control to that clause, executing the associated statements. (If multiple cases match the provided value, the first case that matches is selected, even if the cases are not equal to each other.) If no matching case clause is found, the program looks for the optional default clause, and if found, transfers control to that clause, executing the associated statements. If no default clause is found, the program continues execution at the statement following the end of switch. By convention, the default clause is the last clause, but it does not need to be so.

Answer

switch is shorthand for a bunch of ifs.

switch(n) {
    case x:
        a();
        break;
    case y:
        b();    
        break;
}

... is equivalent to:

if(n == x) {
     a();
} else if(n == y) {
     b();
}

So your first piece of code:

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");}
}

... is equivalent to:

if(n == (n==0 || n==1)) {
   console.log("Number is either 0 or 1");
} else if ( n == ( n >= 2)) {
   console.log("Number is greater than 1");
} else {
   console.log("Default");
}

I hope you can see that n == (n==0 || n==1) and n == ( n >= 2) are both nonsense. If n is 0, for example, the first will evaluate to 0 == true. In many languages this will cause a compiler error (comparing different types). I don't especially want to think about what it does in Javascript!

Your second example:

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");
}

Is equivalent to:

if(true == (n==0 || n==1)) {
    console.log("Number is either 0 or 1");
} else if(true == (n>=2)) {
    console.log("Number is greater than 1");
} else {
    console.log("Default");
}

... in which at least the condition statements true == (n==0 || n==1) and true == (n >=2) make sense.

But this is an unconventional way to use switch in most languages. The normal form is to use the value you're testing as the parameter to switch and for each case to be a possible value for it:

switch(n) {
    case 0:
    case 1:
         console.log("n is 0 or 1");
         break;
    case 2:
         console.log("n is 2);
         break;
    default:
         console.log("n is some other value");
}

However switch doesn't provide a cleverer case than a full equality check. So there's no case >2 && <5.

Your can either use your trick using switch(true) (in Javascript -- there are many languages in which this won't work), or use if/else.

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.