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 case
s and using if
/ else
for more complex logic like you have here. Putting expressions in case
s 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 ofcase
clauses, and executes statements after the firstcase
clause with a matching value, until abreak
statement is encountered. Thedefault
clause of aswitch
statement will be jumped to if nocase
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.