else if adds another condition to an if; JavaScript checks them top to bottom and runs the first block whose condition holds. Order matters: put the highest threshold first. A final else catches the rest.
switch (value) compares one value against fixed case labels. Each case ends with break, or execution falls through into the next case, which is a feature when several labels share a result (stack the cases) and a bug otherwise. default is the catch-all. Inside a function, return in a case does the job of break.
function httpText(code) {
switch (code) {
case 200:
return "OK";
case 404:
return "Not found";
default:
return "Something else";
}
}Your task
Write grade(score) with an else if chain: "A" for 90 and above, "B" for 80, "C" for 70, "D" for 60, else "F". Then write dayType(day) with a switch that returns "weekend" for saturday and sunday, "weekday" for the other five, and "unknown" for anything else, ignoring capital letters.
Hint 1
if (score >= 90) return "A"; else if (score >= 80) return "B"; ...
Hint 2
case "saturday": case "sunday": return "weekend"; stacks two labels on one result.
Show the solution
function grade(score) {
if (score >= 90) return "A";
else if (score >= 80) return "B";
else if (score >= 70) return "C";
else if (score >= 60) return "D";
else return "F";
}
function dayType(day) {
switch (day.toLowerCase()) {
case "saturday":
case "sunday":
return "weekend";
case "monday":
case "tuesday":
case "wednesday":
case "thursday":
case "friday":
return "weekday";
default:
return "unknown";
}
}