Switch-Case for strings in Javascript not working as expected

Posted by Coltin on Stack Overflow See other posts from Stack Overflow or by Coltin
Published on 2010-04-04T00:36:45Z Indexed on 2010/04/04 0:43 UTC
Read the original article Hit count: 488

Filed under:
|
|
|

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?

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about strings