ELSE IF Statements
else if adds further conditions to an if statement, so the code can choose between more than two outcomes. JavaScript tests the conditions from the top down, runs the block of the first one that holds, and skips the rest. A final else catches every case that no condition matched.
const grade = (score) => { if (score >= 70) { return 'distinction'; } else if (score >= 60) { return 'merit'; } else if (score >= 40) { return 'pass'; } else { return 'fail'; }};
console.log(grade(82));console.log(grade(65));console.log(grade(40));console.log(grade(12));This prints:
distinctionmeritpassfailA score of 82 also meets score >= 60 and score >= 40, but those conditions are never tested, because the first one already held.
Order matters
Section titled “Order matters”Because the first match wins, the conditions have to run from the narrowest to the broadest. With the same tests in the opposite order, every passing score stops at the first condition:
const grade = (score) => { if (score >= 40) { return 'pass'; } else if (score >= 60) { return 'merit'; } else if (score >= 70) { return 'distinction'; } else { return 'fail'; }};
console.log(grade(82));This prints:
passChecking for bad input first
Section titled “Checking for bad input first”Put the checks for impossible values at the top, so the later conditions only ever see valid input. Conditions can be combined with || (or) and && (and), which Logical Operators AND and OR covers.
const grade = (score) => { if (typeof score !== 'number' || score < 0 || score > 100) { return 'invalid score'; } else if (score >= 70) { return 'distinction'; } else if (score >= 40) { return 'pass'; } else { return 'fail'; }};
console.log(grade(105));console.log(grade('70'));console.log(grade(71));This prints:
invalid scoreinvalid scoredistinctionIf the check for score > 100 came after the other conditions, a score of 105 would never reach it, because score >= 70 would already have returned 'distinction'.
When to use something else
Section titled “When to use something else”A long chain that compares one value against fixed values, such as status === 'placed', status === 'packed' and so on, often reads better as a switch statement. A chain that only picks one of two values can be a ternary operator.
Steve Griffith covers this topic in his video JavaScript else if Statements.