javascriptswitch-statement

Switch case with less than/greater than not showing correct results


Here is my script

var marks = 11;
switch (marks) {
  case (marks < 20):
    console.log('Yes Freaking Failed');
    break;
  case (marks > 20):
    console.log('Ahh Its Ok');
    break;
  case (marks > 80):
    console.log('Whooping');
    break;
  default:
    console.log('Cant say u maybe Flunked');
    break;
}

I think it should display 'Yes Freaking Failed' because the marks are less than 20. But it shows 'Cant say u maybe Flunked'

Why is that?


Solution

  • When you write

    switch (x) {
    case(y):
        ...
    }
    

    it's equivalent to testing

    if (x === y) {
        ...
    }
    

    So

    case (marks < 20):
    

    means:

    if (marks === (marks < 20)) {
    

    You can't use case for range tests like this, you need to use a series of if/else if:

    if (marks < 20) {
        console.log('Yes Freaking Failed');
    } else if (marks < 80) {
        console.log('Ahh Its OK');
    } else {
        console.log('Whooping');
    }
    

    Also notice that if it worked the way you thought, it could never execute marks > 80, because that would also match marks > 20, and the first matching case is always executed.

    There's no need for the Cant say u maybe flunked case, because there are no other possibilities.