Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Switch-Case for strings in Javascript not working as expected

So I have this problem with strings and switch-case, and I'll try to keep it as simple as possible.

Here event.keyCode has the value "65", and is the result of a keydown event of 'a' (using JQuery).

if (event.keyCode == "65") {    alert("hmmmm"); } 

That works, but:

switch (event.keyCode) {    case '65':       alert("Yay!");       break; } 

That doesn't. However this will work:

switch ('65') {    case '65':       alert("Yay!");       break; } 

And if I do this:

var t = '65'; switch (t) {    case '65':       alert("Yay!");       break; } 

It works. And then I tried this:

var t = event.keyCode; switch (t) {    case '65':       alert("Yay!");       break; } 

But it fails!

So why does it match in the if-block at the beginning, but not for the switch-case?

like image 224
Coltin Avatar asked Apr 04 '10 00:04

Coltin


People also ask

Do switch statements work with Strings JavaScript?

The switch statement compares the String object in its expression with the expressions associated with each case label as if it were using the String. equals method; consequently, the comparison of String objects in switch statements is case sensitive.

Do switch cases work with Strings?

Yes, we can use a switch statement with Strings in Java.

How the switch case condition works in JavaScript?

The switch statement evaluates an expression. The value of the expression is then compared with the values of each case in the structure. If there is a match, the associated block of code is executed. The switch statement is often used together with a break or a default keyword (or both).

What will happen if the switch statement did not match any cases?

If no matching case clause is found, the program looks for the optional default clause, and if found, transfers control to that clause, executing statements following that clause. If no default clause is found, the program continues execution at the statement following the end of switch .


1 Answers

keyCode is an integer, not a string. When you use ==, the conversion is done implicitly. However, the switch uses the equivalent of ===, which doesn't allow implicit conversions. You can test this easily with:

switch (65) {    case '65':       alert("Yay!");       break; } 

As expected, it does not alert.

This is stated in ECMAScript, 5th edition section 12.11 (switch statement). The interpreter will enter a case statement if "input is equal to clauseSelector as defined by the === operator". input is 65 (integer) and clauseSelector is '65' (string) in my above example, which are not ===.

like image 115
Matthew Flaschen Avatar answered Sep 23 '22 19:09

Matthew Flaschen