javascript switch/case : are types compared? [duplicate]

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?

Answers:

Answer

Yes, types are compared.

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

ECMA-262, page 95.

Answer

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

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.