Sub topic 3
Making Decisions with if, else if, and else
This chapter assumes you already know basic JavaScript syntax, how to declare variables with let and const, and how to write and call functions. It also builds on the two chapters before it: how values become truthy or falsy, and how ===, ==, and the relational operators compare values. Here those ideas go to work. The if statement is the basic way JavaScript picks one path over another, and most other branching tools are variations on it.
The Working Model
An if statement evaluates an expression in parentheses. JavaScript converts the result to a boolean using the truthiness rules. If the result is true, it runs the statement that follows. If an else clause is present and the result is false, it runs the statement after else instead.
const temperature = 31;
if (temperature > 30) {
console.log("Hot day");
} else {
console.log("Not that hot");
}
// "Hot day"There are three points to take from this model:
- The condition can be any expression, not only a comparison.
if (items.length)andif (user)are common, and each relies on truthiness. - Exactly one branch of an
if/elseruns. If there is noelse, either the branch runs or nothing does. ifis a statement, not an expression. It produces no value, so you cannot writeconst x = if (a) { 1 } else { 2 }. When you need a value, use the conditional operator, which a later chapter covers.
else if is just a nested if
JavaScript has no special else if keyword. else if is an else whose single statement happens to be another if. These two functions behave identically:
function chained(n) {
if (n < 0) {
return "negative";
} else if (n === 0) {
return "zero";
} else {
return "positive";
}
}
function nested(n) {
if (n < 0) {
return "negative";
} else {
if (n === 0) {
return "zero";
} else {
return "positive";
}
}
}
console.log(chained(0), nested(0)); // "zero" "zero"
console.log(chained(-4), nested(-4)); // "negative" "negative"This explains how a chain behaves. JavaScript tests each condition in order and stops at the first one that is truthy. It never looks at later conditions, even if they would also be true. The final else catches everything that no earlier condition matched.
Order Matters in a Chain
Because the first match wins, you have to order conditions with care. For ranges, test from the most restrictive condition to the least restrictive:
function grade(score) {
if (score >= 90) {
return "A";
} else if (score >= 80) {
return "B";
} else {
return "C or below";
}
}
console.log(grade(85)); // "B"The second condition does not need to say score >= 80 && score < 90. By the time JavaScript reaches it, the first test has already failed, so score < 90 is known to be true. If you reverse the order, the chain breaks:
function badGrade(score) {
if (score >= 80) {
return "B";
} else if (score >= 90) {
return "A"; // unreachable: any score >= 90 already matched above
} else {
return "C or below";
}
}
console.log(badGrade(95)); // "B"Edge Cases: What Falls Through to else
The final else receives every value that failed all the tests. That includes values you may not have expected. Comparisons with NaN are always false, and undefined becomes NaN when it is compared to a number:
function grade(score) {
if (score >= 90) return "A";
else if (score >= 80) return "B";
else return "C or below";
}
console.log(grade(NaN)); // "C or below"
console.log(grade(undefined)); // "C or below"
console.log(grade("85")); // "B" (the string is converted to a number)
console.log(grade("ninety")); // "C or below"A missing or malformed score gets the same answer as a genuine low score. That is usually a bug. If invalid input is possible, give it its own branch before the real logic starts:
function safeGrade(score) {
if (typeof score !== "number" || Number.isNaN(score)) {
return "invalid";
} else if (score >= 90) {
return "A";
} else if (score >= 80) {
return "B";
} else {
return "C or below";
}
}
console.log(safeGrade(undefined)); // "invalid"
console.log(safeGrade("85")); // "invalid"
console.log(safeGrade(72)); // "C or below"Common Errors
Assignment instead of comparison
A single = inside a condition assigns a value. The condition then tests the assigned value. This code silently changes count and never takes the branch:
let count = 5;
if (count = 0) {
console.log("empty");
}
console.log(count); // 0 (the assignment ran, and 0 is falsy)Use === for comparisons. Linters such as ESLint flag this mistake with the no-cond-assign rule.
A stray semicolon after the condition
A semicolon right after if (...) is an empty statement. That empty statement becomes the body of the if. The block that follows is no longer part of the if, so it always runs:
const loggedIn = false;
if (loggedIn); {
console.log("Welcome back"); // runs anyway
}Chained range comparisons
0 < x < 10 does not mean what it means in mathematics. JavaScript evaluates it left to right. 0 < x produces a boolean, and that boolean is then compared to 10 as 1 or 0:
const x = 50;
console.log(0 < x < 10); // true (true < 10 becomes 1 < 10)
console.log(0 < x && x < 10); // false (the correct test)Omitted braces and the dangling else
If a branch holds a single statement, you can leave out the braces. This invites two problems. First, a line you add later looks like part of the branch but is not:
const isAdmin = false;
if (isAdmin)
console.log("Granting access");
console.log("Access granted"); // always runs; indentation is ignoredSecond, an else always attaches to the nearest unmatched if, whatever the indentation suggests:
const a = true;
const b = false;
if (a)
if (b) console.log("a and b");
else
console.log("this else belongs to if (b)"); // printsAlways using braces prevents both problems, and most style guides require them for multi-line branches.
Blocks Create Scope
The braces around a branch form a block. Variables declared with let or const inside a block exist only in that block. var ignores blocks and is scoped to the enclosing function:
function scopeDemo(flag) {
if (flag) {
let inner = "block-scoped";
var outer = "function-scoped";
}
console.log(typeof inner); // "undefined" (inner is not visible here)
console.log(outer); // "function-scoped" or undefined
}
scopeDemo(true); // "undefined", "function-scoped"
scopeDemo(false); // "undefined", undefinedIf a value is set in one of several branches and used after the chain, declare it before the if with let:
function shippingLabel(weightKg) {
let label;
if (weightKg <= 1) {
label = "small";
} else if (weightKg <= 10) {
label = "medium";
} else {
label = "freight";
}
return label;
}
console.log(shippingLabel(4)); // "medium"Chained or Nested?
Use a flat chain when the branches are mutually exclusive outcomes of one question, such as "which grade?" Use nesting when a second question only makes sense after the first has been answered:
function describeOrder(order) {
if (order.paid) {
if (order.shipped) {
return "on its way";
} else {
return "being packed";
}
} else {
return "awaiting payment";
}
}
console.log(describeOrder({ paid: true, shipped: false })); // "being packed"More than two levels of nesting usually makes code hard to read. Later chapters show how guard clauses and lookup tables flatten deeply nested code. When several else if branches all compare one value with ===, a switch statement may also read better.
Summary
| Rule | Consequence |
|---|---|
| The condition is converted to a boolean | Any expression works, so truthiness rules apply |
| `else if` is a nested `if` | Conditions are tested in order, and the first truthy one wins |
| Later conditions can assume earlier ones failed | Order range tests from most to least restrictive |
| `NaN` comparisons are always false | Bad input falls through to `else` unless you test for it |
| `if` is a statement | It produces no value, so you cannot assign its result |
| Braces form a block | `let` and `const` inside a branch are not visible outside it |
Exercise
What does this code print, and why? function size(n) { if (n > 10) { return "big"; } else if (n > 100) { return "huge"; } else { return "small"; } } console.log(size(500));
Show answer
It prints "big". The conditions are tested in order, and 500 > 10 is true, so the first branch returns before n > 100 is ever tested. The "huge" branch can never run. Put the n > 100 test first to fix it.
Exercise
A teammate writes if (age = 18) { console.log("just turned adult"); } with let age = 30;. What happens, and what is the value of age afterwards?
Show answer
The condition assigns 18 to age, and 18 is truthy, so the message always prints. Afterwards age is 18. The intended comparison is age === 18.
Exercise
Rewrite if (0 <= temp <= 100) { console.log("liquid"); } so it works, and explain what the original does when temp is 150.
Show answer
Write if (0 <= temp && temp <= 100) { ... }. In the original, 0 <= 150 evaluates to true, then true <= 100 becomes 1 <= 100, which is true, so 150 is wrongly reported as liquid.