In addition to use !! to force a boolean to enter, you can do this with the switch to evaluate truth / falsity:
switch (true) { // use a boolean to force case statement to evaluate conditionals case (val ? true : false): // force a truthy/falsy evaluation of val using parentheses and the ternary operator console.log(val + ' evaluates as truthy in the switch statement.'); break; default: console.log(val + ' evaluates as falsy in the switch statement.'); break; }
Here are a set of features and tests that you can see for yourself:
(function () { 'use strict'; var truthitizeSwitch = function (val) { switch (true) { // use a boolean to force case statement to evaluate conditionals case (val ? true : false): // force a truthy/falsy evaluation of val using parentheses and the ternary operator console.log(val + ' evaluates as truthy in the switch statement.'); break; default: console.log(val + ' evaluates as falsy in the switch statement.'); break; } return !!val; // use !! to return a coerced boolean }, truthitizeIf = function (val) { if (val) { // if statement naturally forces a truthy/falsy evaluation console.log(val + ' evaluates as truthy in the if statement.'); } else { console.log(val + ' evaluates as falsy in the if statement.'); } return !!val; // use !! to return a coerced boolean }, tests = [ undefined, // falsey: undefined null, // falsey: null parseInt('NaNificate this string'), // falsey: NaN '', // falsey: empty string 0, // falsey: zero false, // falsey: boolean false {}, // truthy: empty object {"foo": "bar"}, // truthy: non-empty object -1, // truthy: negative non-zero number 'asdf', // truthy: non-empty string 1, // truthy: positive non-zero number true // truthy: boolean true ], i; for (i = 0; i < tests.length; i += 1) { truthitizeSwitch(tests[i]); truthitizeIf(tests[i]); } }());
And of course :) mandatory jsFiddle: http://jsfiddle.net/AE8MU/
pete
source share