Life isn't always a simple yes-or-no. Sometimes there are several possibilities. For that, you can chain conditions together with else if:
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:
- Is
73 >= 80? No. Move on. - Is
73 >= 70? Yes! Print "Grade: B" and skip everything else.
Watch what happens if we put the conditions in the wrong order:
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.