Flip your JavaScript Switch

No one likes code conditionals, right? They're difficult to read, extend, and maintain; primarily because they intermingle data with logic. They're why we put up with bloated IOC containers, just to be able to avoid using switch and nested if statements. In JavaScript, we have a better way. Here's a typical switch statement in JS:


var label = switch (dataTypeId) {
case 'revenue' : 'Thousands of USD';
break;
case 'census' : 'Number of Customers';
break;
case 'inventory' : 'Hundreds of Units';
break;
default: '';
}

So we have to deal with ubiquitous break token, the extra case structure, and lengthy code bloat to make a simple decision. Got code smell? Here's the alternative, use object prototypal extension and JSON interpretation to create a hash instead.


var labelOptions = {
'revenue' : 'Thousands of USD',
'census' : 'Number of Customers',
'inventory' : 'Hundred of Units'
}
var label = labelOptions[dataTypeId] || '';

Et voila! We have separation of concerns, data and logic. We have easy extension by adding another property to our labelOptions object. We have more streamlined code without intermingled execution tokens and is easier to grok. Thanks to JavaScript's treatment of functions as data type, you could even return functions instead of simple expressions. So before you reach for that switch construct again, think about hashing instead.