Replacing If Else Chains with Switch If you have many options to choose from code example
Example 1: Replacing If Else Chains with Switch
function chainToSwitch(val) {
var answer = "";
if (val === "bob") {
answer = "Marley";
} else if (val === 42) {
answer = "The Answer";
} else if (val === 1) {
answer = "There is no #1";
}
switch(val){
case "bob":
answer = "Marley";
break;
case 42:
answer = "The Answer";
break;
case 1:
answer = "There is no #1";
break;
}
return answer;
}
Example 2: Replacing If Else Chains with Switch
function chainToSwitch(val) {
var answer = "";
switch(val){
case "bob":
answer = "Marley";
break;
case 42:
answer = "The Answer";
break;
case 1:
answer = "There is no #1";
break;
case 99:
answer = "Missed me by this much!";
break;
case "John":
answer = "";
break;
case 156:
answer = "";
break;
default:
answer = "Ate Nine";
}
return answer;
}
chainToSwitch(7);