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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With