Switch operator and type of enforcement

I read in Professional JavaScript for Web Developers by Nikolai Zakas in p. 78 of the third edition (the latter, I think):

The switch statement compares the values ​​using equal equal operators, so no type coercion occurs (for example, the string "10" is not equal to the number 10).

I made a few simple switch statements just for confirmation, and the result was different:

var num = "9"; switch (true) { case num < 0: alert("less than 0"); break; case num >= 0 && num <10: alert("between 0 and 10"); break; default: alert("False"); } 

https://jsfiddle.net/pbxyvjyf/

Thus, forced enforcement is performed: alert("between 0 and 10") is selected. Have the rules changed or am I doing something wrong?

+6
source share
5 answers

This will return false :

 var num = "9"; switch (num) { case num < 0: alert("less than 0"); break; case num >= 0 && num <10: alert("between 0 and 10"); break; default: alert("False"); } 

Therefore, the author is right.

+6
source

your case statements return a boolean, so the type is correct

num >= 0 && num <10 - returns true or false

but if i did it

 switch (1) { case "1": console.log("never get here"); break; case 1: console.log("but this works"); break; } 
+8
source

You really are not using the switch statement as intended. There must be an expression that was evaluated on the switch, and cases check the possible values. This is from one of the canonical examples:

 switch (new Date().getDay()) {    case 0:      day = "Sunday";        break;    case 1:      day = "Monday";        break;    case 2:      day = "Tuesday";        break;    case 3:      day = "Wednesday";        break;    case 4:      day = "Thursday";        break;    case 5:      day = "Friday";        break;    case 6:      day = "Saturday"; } 

You use the switch statement more than a bunch of ifs.

+3
source

What this line of documentation means is that when matching the switch value with each case value, type coercion is not applied.

If the case expression itself is an expression that will include type coercion, then, obviously, coercive coercion will take place. num >= 0 && num <10 evaluates to true , but when using true for true it will use the "identically equal" operator at the top of the switch . Since true identically equal to true , the control flow goes into this case .

+3
source

Not a javascript expert, but I believe that the rule mentioned by the author is valid in this case, for example:

  var num = "9"; switch(num){ case 9: alert("Yes the number is equal to: 9"); break; default: alert("False"); } 

If you try to run this code, you will see that a second warning appears.

I hope I helped you .. :)

+1
source

All Articles