Home > front end >  Why switch false always return first case?
Why switch false always return first case?

Time:01-03

I'm trying to understand switch behaviour when it deals with false.

let grade = 65;

switch(false){
  case grade >= 90:
    console.log(grade);
    console.log("You did great!");
    break;
  case grade >= 80:
    console.log("You did good!");
    break;
  default:
    console.log(grade, "is not a letter grade!");

I don't understand why grade will always hit first case in the code above

I was expecting none of the case being fulfilled because of switch(false), and there should be no console log printed.

CodePudding user response:

swtich compares the expression in the case with the value passed to switch.

(grade >= 90) === false


I strongly recommend only using simple values in cases and using if / else for more complex logic like you have here. Putting expressions in cases is unintuative.

CodePudding user response:

You need to check against the opposite of the expression, because of the double negation.

switch (false) {
    case !(grade >= 90): // code
}

vs

switch (true) {
    case grade >= 90: // code
}

CodePudding user response:

From MDN:

The switch statement evaluates an expression, matching the expression's value against a series of case clauses, and executes statements after the first case clause with a matching value, until a break statement is encountered. The default clause of a switch statement will be jumped to if no case matches the expression's value.

More details here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/switch

CodePudding user response:

It's because, it compares passed value (false) with case equation (which is also false in first case), so false === false is true (Yes it's ===, not ==), so it's going into the first case.

  • Related