else if: More Than Two Choices

Grade 4, page 3 of 11. A one-minute read.

Life isn't always a simple yes-or-no. Sometimes there are several possibilities. For that, you can chain conditions together with else if:

JavaScript
const score = 73;

if (score >= 80) {
  console.log("Grade: A 🌟");
} else if (score >= 70) {
  console.log("Grade: B 👍");
} else if (score >= 60) {
  console.log("Grade: C 🙂");
} else if (score >= 50) {
  console.log("Grade: D 😬");
} else {
  console.log("Grade: F 📚 Time to hit the books!");
}

It prints

Grade: B 👍

JavaScript checks each condition from top to bottom, and runs the block for the first one that's true. Then it skips all the rest. If none of them are true, the final else block runs (you don't have to include a final else, but it's often a good idea).

So with a score of 73:

  1. Is 73 >= 80? No. Move on.
  2. Is 73 >= 70? Yes! Print "Grade: B" and skip everything else.
Watch outOrder matters!

Watch what happens if we put the conditions in the wrong order:

JavaScriptHas a bug
const score = 95;

if (score >= 50) {
  console.log("Grade: D");
} else if (score >= 80) {
  console.log("Grade: A");
}

It prints

Grade: D

A score of 95 gets a D! Because 95 >= 50 is true, the very first block runs, and the rest are skipped. When your conditions overlap, always check the most specific (or highest) one first.

Reading is step one

CurlyScript turns these notes into a game: short questions, an explanation after every answer, and a test at the end of each grade. Free, with nothing to sign up for.

Start learning