31

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?

1
  • What is your context testing ? Commented Apr 4, 2010 at 0:41

1 Answer 1

59

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

Sign up to request clarification or add additional context in comments.

2 Comments

You're right, I'm used to things crashing when I compare (int == string). Thanks!
@2-Stroker, just switch directly on the number. It may be faster too.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.