I read in the 'Professional JavaScript for Web Developers' by Nicholas Zakas in p.78 of 3rd edition (last one I think):
The switch statement compares values using the identically equal operator, so no type coercion occurs (for example the string "10" is not equal to the number 10).
I made up some simple switch statement just to confirm 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/
So, type coercion is done: the alert("between 0 and 10")
is chosen.
Have the rules changed or am I doing something wrong?
Type coercion can be explicit and implicit. When a developer expresses the intention to convert between types by writing the appropriate code, like Number(value) , it's called explicit type coercion (or type casting).
Type coercion is the automatic or implicit conversion of values from one data type to another (such as strings to numbers).
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.
Type Coercion refers to the process of automatic or implicit conversion of values from one data type to another. This includes conversion from Number to String, String to Number, Boolean to Number etc. when different types of operators are applied to the values.
your case statements return a boolean so the type is correct
num >= 0 && num <10
- returns true or false
but if i would do this
switch (1) {
case "1":
console.log("never get here");
break;
case 1:
console.log("but this works");
break;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With