I don't understand why the switch or equivalent is so popular in languages. To me, it seems like it had a place back in the days when the alternative was lots of nested if statements in the else part of other if statements. Now that we have else if, why do we need it?
If we take the following:
switch (expr) {
case "Oranges":
document.write("Oranges are $0.59 a pound.<br>");
break;
case "Apples":
document.write("Apples are $0.32 a pound.<br>");
break;
case "Bananas":
document.write("Bananas are $0.48 a pound.<br>");
break;
default:
document.write("Sorry, we are out of " + expr + ".<br>");
}
It is clearly more readable than below?
if (expr == "Oranges") {
document.write("Oranges are $0.59 a pound.<br>");
} else {
if (expr == "Apples") {
document.write("Apples are $0.32 a pound.<br>");
} else {
if (expr == "Bananas") {
document.write("Bananas are $0.48 a pound.<br>");
} else {
document.write("Sorry, we are out of " + expr + ".<br>");
}
}
}
But how is it more readable than:
if (expr == "Oranges") {
document.write("Oranges are $0.59 a pound.<br>");
} else if (expr == "Apples") {
document.write("Apples are $0.32 a pound.<br>");
} else if (expr == "Bananas") {
document.write("Bananas are $0.48 a pound.<br>");
} else {
document.write("Sorry, we are out of " + expr + ".<br>");
}