Switch Case not showing correct results

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.

Leave a Comment