else and else if
- Node.js course
- Beginner
- Lesson 37/116
- 4 min
Learn else and else if chains for alternative cases.
The else statement
To run a different block when the if condition is false you use else. The form is if (condition) { ... } else { ... }. Exactly one of the two blocks runs.
For example if (score >= 50) { console.log("Pass"); } else { console.log("Fail"); } prints "Pass" when score is at least 50 and "Fail" otherwise. The else block runs only when the if condition is false; it has no condition of its own.
else if chains
To test more than two cases you build a chain with else if. The first condition that is true has its block run; the rest are skipped. The form is if (c1) { ... } else if (c2) { ... } else { ... }.
For example a grade calculation: if (score >= 90) { ... "A" } else if (score >= 80) { ... "B" } else { ... "C" }. Conditions are checked top to bottom; the first true one determines the result. This structure is ideal for cases split into ranges.
Practice Compute the grade letter
The score variable is set to 85. Write an if/else if/else chain: call console.log("A") when score >= 90, console.log("B") when score >= 80, otherwise console.log("C"). The output on a single line must be B.
Starter code
const score = 85;
// Write the if/else if/else chain hereSample solution
const score = 85;
if (score >= 90) {
console.log("A");
} else if (score >= 80) {
console.log("B");
} else {
console.log("C");
}Expected output
B
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Write the else block
if (score >= 50) {
console.log("Pass");
} ____ {
console.log("Fail");
}
if (score >= 50) {
console.log("Pass");
} else {
console.log("Fail");
}
Explanation: else runs when the if condition is false.
2 What is the output when score = 75?
if (score >= 90) { console.log("A"); }
else if (score >= 80) { console.log("B"); }
else { console.log("C"); }- A
- C Correct answer
- B
- 75
Explanation: 75 reaches neither 90 nor 80; the else block prints "C".
3 Match each construct to its job
| Term | Meaning |
|---|---|
if (c) |
Tests first condition |
else if (c) |
Tests next condition |
else |
When none matched |
{ } |
Code block |