Fortunately JavaScript offers the simplicity and elegance of Object literals as an 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";
break;
case "Rain":
whatToBring ="Umbrella and boots"
break;
case "Cold":
whatToBring = "Scarf and Gloves";
break;
default : whatToBring = "Play it by ear";
}
switch(weather){
case "Sunny":
whatToBring = "Sunscreen and hat";
break;
case "Rain":
whatToBring ="Umbrella and boots"
break;
case "Cold":
whatToBring = "Scarf and Gloves";
break;
default : whatToBring = "Play it by ear";
}
Example 2: Pull data into object construct. Logic becomes clean
var gear = {
"Sunny" : "Sunscreen and hat",
"Rain" : "Umbrella and boots",
"Cold" : "Scarf and Gloves",
"Default" : "Play it by ear"
}
var whatToBring =
gear[weather] ? gear[weather] : gear["Default"];
"Sunny" : "Sunscreen and hat",
"Rain" : "Umbrella and boots",
"Cold" : "Scarf and Gloves",
"Default" : "Play it by ear"
}
var whatToBring =
gear[weather] ? gear[weather] : gear["Default"];
In the interest of pure parallelism, shouldn't "testCase" in Example 1 be changed to "weather"? Then it's clear that Example 2 is not introducing a new "weather" variable that wasn't needed in Example 1.
ReplyDeleteThanks Matt - good point. Done.
ReplyDelete