Does the Javascript switch statement compare strictly or by type-converting?
Asked
Active
Viewed 1,758 times
1
-
It uses [strict comparison](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/switch) (`===`) – Tom Fenech Aug 08 '14 at 08:59
-
1Surely this is trivial to test, what does `switch ("1") { case 1: alert(1); break; }` do? – Alex K. Aug 08 '14 at 08:59
-
1Perhaps check [*ES5*](http://ecma-international.org/ecma-262/5.1/#sec-12.11): "If *input* is equal to *clauseSelector* as defined by the === operator, then…". – RobG Aug 08 '14 at 09:11
3 Answers
6
It only uses strict comparison. In particular, it never falls back to type coercion even when no strict matches are found — it will immediately skip to the default clause, if any. From MDN:
The program first looks for a
case
clause whose expression evaluates to the same value as the input expression (using strict comparison,===
) and then transfers control to that clause, executing the associated statements. If no matchingcase
clause is found, the program looks for the optionaldefault
clause...

BoltClock
- 700,868
- 160
- 1,392
- 1,356
6
I can't believe it was faster to ask this question than it was to just try this:
var v = "1";
switch (v) {
case 1:
alert ("No");
break;
default:
alert ("Yes");
}
In answer to your question, it's ===
.

Grim...
- 16,518
- 7
- 45
- 61
-
5The problem with "just trying it" is that in the absence of specified behavior, you're only testing the particular implementation. In this case it looks to actually be *specified* that strict comparison is to be used, but in another case, the standard might not be as clear or even say anything at all in which case you risk digging yourself into a hole if you "just test" and then assume that all implementations are alike. – user Aug 08 '14 at 09:17
-
@MichaelKjörling The reverse is also true, of course - if you checked the spec and saw the comparison was strict but your environment was not, you could have a horrible time debugging. – Grim... Aug 08 '14 at 09:19