Reputation: 43
I am planning to use a switch statement similar to the one in the experimental function (testIfFalsy) below, which I wrote to test how such a switch statement would evaluate the 'truthiness' or 'falsehood' of certain numeric values that I expected to throw at it. I know that this form of switch statement "switch (true)" is somewhat unorthodox, but it is not an illegal use of switch and it is highly desirable both for readability of the code and for the type of data I'm expecting to use it with. I have done the same thing before, quite successfully, with BASIC's case statement, and I am now porting the same source code to Javascript.
The comments within each of the switch's "case" clauses list the values that were caught by that clause. I got some unexpected results from this code. Firstly, when I wrote it, I never expected to see values caught by the "default" clause, because that would mean that they slipped past both of the previous case clauses, and hence were being interpreted as being neither true nor false! But as the comments show, there were indeed such values.
The strangest result of all, is how the numeric literal 1 is treated. An "if(a)" condition treats the variable a as being true when its value is numeric 1, as demonstrated in this code by the alert saying, "a is true," executed prior to the switch statement. Also, the second alert in the "default" clause of the switch displays "true," showing that the statement "Boolean(a)" also treats a numeric value of 1 as true. So why is this switch statement treating it as neither true nor false?
function myCallingFunction() {
var R;
// unrelated code ...
// Tail end of calling function
R = testIfFalsy(0);
}
function testIfFalsy(a) {
if (a) {alert ("a is true");}
switch (true) {
case (!a):
alert ("it's true that a is false, a=" + a);
// when arg is: NaN, undefined, null, 0, -0, 0/0, false, !1 , '', R
// value shown= NaN, undefined, null, 0, 0, NaN, false, false, , undefined
break;
case (a):
alert ("it's true that a is true. a=" + a);
// when arg is: true, !0,
// value shown= true, true,
break;
default:
alert ("a is neither true nor false, a=" + a);
alert (Boolean(a));
// when arg is: 1,2,-1,-2, 'cat', 'NaN', [0],
// value shown= 1,2,-1,-2, cat , NaN , 0 ,
}
}
Upvotes: 1
Views: 897
Reputation: 98
Although I am not sure, the reason seems to be that switch does not perform implicit coercion. Boolean() might as well be considered explicit, as it was written to accept values other than booleans. Again, I'm not sure, but a quick fiddle might confirm the suspicion.
Upvotes: 2