Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Switch statement and type coercion

Tags:

javascript

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?

like image 862
viery365 Avatar asked Jun 23 '16 15:06

viery365


People also ask

What are the types of coercion?

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).

What is type coercion in JavaScript?

Type coercion is the automatic or implicit conversion of values from one data type to another (such as strings to numbers).

What are switch statements used for?

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.

How does coercion work in JavaScript?

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.


1 Answers

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;

} 
like image 98
WalksAway Avatar answered Oct 13 '22 01:10

WalksAway