Tag: Switch

The Case against Switch

I’ve never been fond of switch statements, whether in JavaScript or Java. They’re big and hard to follow, and of course if you forget the break keyword after each case you enter fall-through hell. (Since break statements are almost always intended it seems a pain to have to add them manually). Using objects as hash table for look-up is a simple and elegant alternative:

Example 1: Using switch is hard to read and the data is mixed with the logic

var whatToBring;
switch(weather) {
    case "Sunny":
        whatToBring = "Sunscreen and hat";
    case "Rain":
        whatToBring  ="Umbrella and boots"
    case "Cold":
        whatToBring = "Scarf and Gloves";
    default : whatToBring = "Play it by ear";

Example 2: Pull data into object construct. Data and logic are separated.

var whatToBring = {
    "Sunny" : "Sunscreen and hat",
    "Rain" : "Umbrella and boots",
    "Cold" : "Scarf and Gloves",
    "Default" : "Play it by ear"

var gear = whatToBring[weather] || whatToBring["Default"];