Sub topic 3
Making Decisions with if, else if, and else
This chapter assumes you can write functions and that you know the earlier material on truthy and falsy values and on === versus ==. An if statement runs a block of code only when its condition is truthy. The condition doesn't have to be a boolean. JavaScript converts whatever value you give it using the truthiness rules.
The basic shape
An if can stand alone, or you can pair it with an else that runs when the condition is falsy:
function describeCart(items) {
if (items.length) {
return `You have ${items.length} item(s).`;
} else {
return "Your cart is empty.";
}
}
console.log(describeCart(["book"])); // "You have 1 item(s)."
console.log(describeCart([])); // "Your cart is empty."Here items.length is a number. A length of 0 is falsy and any other length is truthy, so this code doesn't need a comparison.
Chaining with else if
When there are more than two outcomes, chain conditions with else if. JavaScript checks them from top to bottom and runs only the first branch whose condition is true. It skips everything after that branch, even conditions that would also be true.
function grade(score) {
if (score >= 90) {
return "A";
} else if (score >= 80) {
return "B";
} else {
return "C or below";
}
}
console.log(grade(85)); // "B"else if is not a separate keyword. It is an else whose body is another if statement, so a chain is really a series of nested if/else statements written flat.
Order matters
Since the first match wins, put the narrower conditions first. This version is wrong:
function gradeWrong(score) {
if (score >= 80) {
return "B";
} else if (score >= 90) {
return "A"; // unreachable: any score >= 90 already matched above
}
return "C or below";
}
console.log(gradeWrong(95)); // "B"Common errors
| Mistake | What happens | Fix |
|---|---|---|
| `if (x = 5)` | This assigns 5 to `x`. The condition is then always truthy. | Use `===` |
| `if (ready);` followed by a block | The stray semicolon is an empty statement, so the block always runs. | Remove the semicolon |
| Leaving out the braces when there are two lines | Only the first line is controlled by the `if`. | Always use braces |
| Overlapping conditions in the wrong order | A later branch is never reached. | Test the narrowest condition first |
The missing-braces error is easy to miss when reading code:
let loggedIn = false;
if (loggedIn)
console.log("Welcome back");
console.log("Loading dashboard"); // runs anyway: not part of the ifReturning early instead of nesting
When each branch ends with return, the else is redundant. The function has already exited by the time the next condition is tested:
function grade2(score) {
if (score >= 90) return "A";
if (score >= 80) return "B";
return "C or below";
}
console.log(grade2(72)); // "C or below"Both versions behave the same. Choose whichever is easier to read in context. A later chapter builds on this style with guard clauses.
Exercise
What does check(0) return, and why?
function check(n) { if (n) { return "has value"; } else if (n === 0) { return "zero"; } else { return "nothing"; } }
Show answer
It returns "zero". 0 is falsy, so the first branch is skipped. Then 0 === 0 is true, so the second branch runs.
Exercise
Rewrite if (temp > 30) { label = "hot"; } else if (temp > 15) { label = "mild"; } else { label = "cold"; } so that it still works if someone swaps the first two conditions.
Show answer
Make each condition exclusive. Use temp > 30 for "hot" and temp > 15 && temp <= 30 for "mild". Then the order no longer changes the result.