else and else if
Learn else and else if chains for alternative cases.
else: when the condition is false
By adding an else block to an if statement, you specify the code that runs when the condition is false. The program then chooses one of two paths.
if (age >= 18) {
console.log("Can drive");
} else {
console.log("You must wait");
}When the condition is true the if block runs; when it is false the else block runs. Both never run together.
Conditional chains with else if
When there are more than two cases, you add new conditions with else if. This structure is called a conditional chain. JavaScript reads from top to bottom and runs the first block whose condition is true.
if (score >= 85) {
console.log("AA");
} else if (score >= 70) {
console.log("BA");
} else if (score >= 50) {
console.log("CB");
} else {
console.log("FF");
}Order matters: the highest threshold is tested first. If score = 75, the first condition is false, the second is true, and 'BA' is logged.
Exercise Write a grade calculation chain
Write a grade chain for the score variable. 85 and above is 'AA', 70-84 is 'BA', 50-69 is 'CB', below is 'FF'. Log each branch with console.log. Use if, at least one else if, and else.
Show example solution
let score = 75;
if (score >= 85) {
console.log("AA");
} else if (score >= 70) {
console.log("BA");
} else if (score >= 50) {
console.log("CB");
} else {
console.log("FF");
}
Test yourself
-
if (x > 10) { A } else { B } - what happens when x = 5?
- Block A runs
- Both run
- Neither runs
- Block B runs
Show answer
Block B runs — Correct. Since x = 5, x > 10 is false; the else block B runs.
-
Add a new branch with else if
let score = 75; if (score >= 85) { console.log("AA"); }____ if (score >= 70) { console.log("BA"); }Show answer
let score = 75; if (score >= 85) { console.log("AA"); }else if if (score >= 70) { console.log("BA"); } -
Match if/else if/else to their roles
- if
- Tests the first condition
- else if
- Adds a second condition
- else
- Runs when no condition matches
- condition
- An expression returning true/false