AI Hints
JavaScript · Lesson 20 of 138

else if and else

More choices.

⏱ 2 min read▶ Video at 23:49🎓 Free
Watch this lesson in the JavaScript courseWatch on YouTube ↗Full JavaScript course

Often there are more than two possibilities. A grade could be an A, a B, a C, or a fail. Else if adds more conditions, and else catches everything that's left.

else if and else
From the video: else if and else
  • More than two choices
  • else if adds conditions
  • else catches the rest

A grade

JavaScript checks each condition from the top, in order. The first one that's true runs, and the rest are skipped. If none are true, the else block runs. Run it. Seventy eight isn't ninety or more, and it isn't eighty or more, but it is seventy or more. So it's a C.

app.jsjavascript
const score = 78;

if (score >= 90) {
  console.log("A");
} else if (score >= 80) {
  console.log("B");
} else if (score >= 70) {
  console.log("C");
} else {
  console.log("Keep practising");
}
Output
C

Order matters

Because the first true condition wins, put the most specific checks first. If we checked score greater than or equal to seventy first, a score of ninety five would get a C. Always test the boundaries, like exactly eighty, and exactly ninety.

keyvalue
iffirst check
else ifnext checks, in order
elsenothing else matched
First truewins

Summary

Else if adds more conditions, checked in order, and else handles everything else. Next, combining conditions with and, or, and not.

Key takeaways
  • if / else if / else
  • First true wins
  • Test the boundaries
Next up: Logical Operators — &&, ||, !