Syntax
if (condition) { } else if (condition) { } else { }
switch (value) { case x: break; default: }Examples
if...else if...else
Handling multiple conditions in sequence.
function getGrade(score) {
if (score >= 90) {
return "A";
} else if (score >= 80) {
return "B";
} else if (score >= 70) {
return "C";
} else {
return "F";
}
}
console.log(getGrade(85)); // "B"switch Statement
Checking one value against several discrete cases.
function getDayName(day) {
switch (day) {
case 0:
return "Sunday";
case 1:
return "Monday";
case 2:
return "Tuesday";
default:
return "Unknown";
}
}
console.log(getDayName(1)); // "Monday"
// Fall-through: cases without break share the same code
function isWeekend(day) {
switch (day) {
case 0:
case 6:
return true;
default:
return false;
}
}Best practices
- Use switch when comparing one value against many discrete options - it is more readable than a long if/else if chain in that case
- Never forget the break statement in each switch case, or execution will fall through into the next case unintentionally
- Always include a default case in a switch to handle unexpected values
- For simple boolean conditions, prefer if/else or a ternary over switch
Runtime & versions
Browsers and JavaScript runtimes. Feature availability depends on the language and runtime version used by your project; consult the official reference below.
ECMAScript specification