Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the purpose of boolean switch statements in JavaScript?

I just encountered a boolean switch statement in someone else's JavaScript code. It looked a little bit like this:

switch (a || b) {
  case true:
    // do some stuff
  break;
  default:
    // do other stuff
  break;
}

I haven't been programming for very long, but I certainly have never seen anything like this before. It seems kind of stupid, but I would like to give the programmer the benefit of the doubt. Is there any functional difference between the above code and the following:

if (a || b) {
  // do some stuff
}
else {
  // do other stuff
}

And if there is, what is it?

like image 922
thismax Avatar asked Dec 16 '10 13:12

thismax


1 Answers

Yes, there's a difference. Taking your example into account,

var a = 0,
    b = 1;

Now let's look at the switch statement:

switch (a || b) {

When this switch statement is run, the expression a || b is evaluated. || is a short-circuit operator, it will return the left operand's value if it's "truthy", else it will return the right operand's value. In this case, a = 0, so b will be returned (1). Now look at the case statement:

case true:

When evaluating case statements, no type coercion is performed on either value and strict equality is assumed. In our example, this is the same as writing 1 === true, so the code following the case statement is never run. So let's take a look at the if statement:

if (a || b) {

For an if statement, the conditional expression a || b is evaluated and then the result is converted to a boolean. Internally, this looks like ToBoolean(a || b). Since a || b evaluates to 1 and coercion of 1 to a boolean is true, the condition passes and the block executes.

A better equivalent would be:

if ((a || b) === true) {
    // do some stuff
}
else {
    // do other stuff
}

As already pointed out, in situations where there are many cases and types could vary, a switch statement could be useful. Such a situation would be rare, however.

like image 102
Andy E Avatar answered Oct 05 '22 23:10

Andy E