10

Possible Duplicate:
Is it safe to assume strict comparison in a Javascript switch statement?

Does a switch/case statement in javascript compare types or only values?

In other words, when I have the following code:

switch (variable)
{
    case "0": [...] break;
    case "1": [...] break;
    default: [...] break;
}

is it equivalent to

if ( variable == "0" )
{
    [...]
}
else if ( variable == "1" )
{
    [...]
}
else
{
    [...]
}

or to

if ( variable === "0" )
{
    [...]
}
else if ( variable === "1" )
{
    [...]
}
else
{
    [...]
}

edit: is there a way to force compare values and types at once?

Community
  • 1
  • 1
iliaden
  • 3,791
  • 8
  • 38
  • 50
  • 8
    You can easily test it... – gdoron Jun 13 '12 at 16:17
  • 3
    Yes, it would have taken less time to type in a jsfiddle than it did to type in the question :-) – Pointy Jun 13 '12 at 16:20
  • @amnotiam. How do you find them...? have you seen it before? – gdoron Jun 13 '12 at 16:26
  • @gdoron: No, just did [this search](http://stackoverflow.com/search?q=javascript+switch+type+comparison). It's the first result. :) –  Jun 13 '12 at 16:28
  • @amnotiam, But this way you don't get reputation... `:)` – gdoron Jun 13 '12 at 17:01
  • 1
    @gdoron Please compare the implications of "I tested it, it works on my machine" with "It's specified in the language." Pointing this out as a duplicate is a fair point, but "please save yourself the time and test it yourself" is not. – awendt Nov 22 '17 at 08:53

2 Answers2

15

Yes, types are compared.

If input is equal to clauseSelector as defined by the === operator, then set found to true.

ECMA-262, page 95.

Oleg V. Volkov
  • 21,719
  • 4
  • 44
  • 68
1

It checks types as well,

Example:

var x = false;

switch (x) {
case "":
    alert('x'); /// Not happening
    break;
case false:
    alert('y');  // happen
    break;
}​

Live DEMO

And as the spec says:

If input is equal to clauseSelector as defined by the === operator, then...

Community
  • 1
  • 1
gdoron
  • 147,333
  • 58
  • 291
  • 367