Monday, June 11, 2012

In javascript, switch and if are not equivalent. The switch statement is type exact.

It was not a complete surprise, but I did not expect it, either: the switch statement in Javascript is type exact, meaning that a classic if block like this:
if (x==1) { 
  doSomething() 
} else { 
  doSomethingElse(); 
}
is not equivalent to
switch(x) {
  case 1:
    doSomething();
    break;
  default:
    doSomethingElse();
    break;
}
If x is a string with the value '1' the if will do something, while the switch will do something else (pardon the pun). The equivalent if block for the switch statement would be:
if (x===1) { 
  doSomething() 
} else { 
  doSomethingElse(); 
}
(Notice the triple equality sign, which is type exact)

Just needed to be said.

2 comments:

Alex Peta said...

Triple equal(===) is the same as calling "Object.ReferenceEquals()"(C#) rather then just comparing the values with the double equal(==).

The same thing applies to not operator : (!==) versus (!=).

Siderite said...

No, it is not the same. === is equivalent to == in C# :-)

It might be confusing to think of similarities with methods that are designed almost exclusively for complex objects and not simple value objects, hence the 'Reference' name.

"1"==1 will be true, yet "1"===1 will be false; it checks that the types of the values are also the same.