Explain it simply
Explain it simply
It is like glancing at the clock before you greet someone. In the morning you say "Good morning", in the afternoon "Good afternoon", and otherwise "Good evening". if...else lets a program make the same kind of decision.
The program tests a condition whose answer is true or false. If it is true, one block of code runs; if not, the program moves on to the next condition. However many branches there are, exactly one of them runs.
Problem → Why → Solution
The problem: "Good afternoon" at 9 AM
While tidying the greeting code, a developer changed the order of the conditions. Now every user who opens the app at 9 AM sees "Good afternoon!". There is no error and no warning: the "Good morning!" branch simply never runs again.
const time = 9;
if (time < 18) {
console.log("Good afternoon!"); // also catches 9 AM
} else if (time < 12) {
console.log("Good morning!"); // can never run
} else {
console.log("Good evening!");
}Why is the morning branch unreachable?
An else if chain is checked from top to bottom and stops at the first true condition. Every time below 12 is also below 18, so the wider test catches it first and the narrower branch can never be reached. JavaScript does not warn about unreachable branches, so you must order the conditions yourself, from the narrowest to the widest.
Core concept: the first true branch wins
In if (condition) { ... }, the condition can be any expression. JavaScript evaluates it, turns the result into true or false, and runs the block when it is true. An else block runs when the condition is false. Chaining else if branches creates a chain in which only the first true branch runs and every other branch is skipped. The final else is optional and acts as a catch-all when nothing matched.
When the condition is not a boolean, JavaScript converts it with the truthy/falsy rules. There are only eight falsy values; everything else is truthy, including "0", "false", an empty array [] and an empty object {}. So if (name) is a handy test for a non-empty string, but if (count) treats 0 as "nothing". To see how JavaScript will judge any value, call Boolean(value) or its shorthand !!value: Boolean("0") is true while Boolean(0) is false.
| Falsy value | Where it usually comes from |
|---|---|
| false | The result of a comparison |
| 0, -0, 0n | A zero count or balance |
| "" | An empty form field |
| null, undefined | Missing or not yet assigned |
| NaN | A failed Number() conversion |
Conditions are built from comparison and logical operators, as in if (age >= 18 && hasTicket). Writing a range with both bounds, such as time >= 12 && time < 18, makes a branch independent of the order of the chain. Braces are optional for a single statement, but a line added later will look as if it is inside the block while it actually always runs, so always use braces. Use if to perform an action, and the ternary operator to pick one of two values: const label = time < 12 ? "AM" : "PM";. Avoid nesting one ternary inside another.
- Evaluate the first condition
- Convert it to true or false
- First true branch runs; rest skipped
- Nothing matched: the else block runs
A chain never runs more than one branch.
General pattern
if (conditionA) {
// runs when conditionA is truthy
} else if (conditionB) {
// runs when A was falsy and B is truthy
} else {
// runs when nothing above matched
}
const value = condition ? valueIfTrue : valueIfFalse;You can add as many else if branches as you need, and the else is optional. The last line is not an if statement but an expression, so it produces a value.
Example: a greeting that depends on the time
In this example the conditions are ordered from the narrowest, which is what makes every branch reachable. Change time from 14 to 9, 12, 18 and 23 in turn and predict the branch each time; boundary values such as 12 and 18 matter most.
const time = 14;
if (time < 12) {
console.log("Good morning!");
} else if (time < 18) {
console.log("Good afternoon!");
} else {
console.log("Good evening!");
}Code breakdown
- Line 1
const time = 14;An hour in 24-hour format: 14 is 2 PM. A real app would get it from new Date().getHours().
- Line 3
if (time < 12) {14 < 12 is false, so this block is skipped and the next condition is tested.
- Line 5
} else if (time < 18) {Reaching this line already guarantees that time is not below 12, so time < 18 alone means the range 12 to 17. 14 < 18 is true, so it prints "Good afternoon!".
- Line 7
} else {Runs only when both conditions above were false, which means 18 and later. In this run an earlier branch already matched, so it is never even considered.
Good afternoon!- Read time
- time < 12? (false)
- time < 18? (true)
- Print "Good afternoon!" and leave the chain
time < 12
Good morning!
12 <= time < 18
Good afternoon!
time >= 18
Good evening!
Line up checks instead of nesting them
Beginners often put an if inside an if inside an if, producing a pyramid that drifts to the right. Usually a flat chain reads better: check each problem case first, one at a time, and leave the success path for the final else.
const isLoggedIn = true;
const cartItems = 3;
const balance = 20;
const total = 35;
if (!isLoggedIn) {
console.log("Please log in first");
} else if (cartItems === 0) {
console.log("Your cart is empty");
} else if (balance < total) {
console.log(`You need ${total - balance} more`); // You need 15 more
} else {
console.log("Order placed");
}Each branch handles exactly one situation, so adding a new rule later means adding one more else if. Compare that with the nested version, where the same four outcomes would sit three levels deep and every closing brace would need a comment to say which check it ends.
In real projects
Where this shows up in real projects
Form validation is full of if chains: one message for an empty email, another for a missing @, another for a short password. Access control uses checks such as if (user.role === "admin") to decide which buttons to show, and pricing pages pick a discount tier from quantity ranges.
Responses from a server are branched on their status code: show the data on 200, a "not found" page on 404, a retry message on 500. Feature flags show a new feature to some users with a simple condition such as if (flags.newCheckout). In code review, the boundary values of these branches get the most scrutiny, because the difference between >= and > really does reach users.
Common mistakes
Common mistakes
1. Writing = instead of === in a condition
if (role = "admin") does not compare: it stores "admin" in role. The assignment's result, "admin", is truthy, so every user becomes an admin. Always use === inside a condition.
2. Ordering range conditions wrongly
As the problem section showed, a wider test hides a narrower one below it. Order from the narrowest, or give every branch both bounds.
3. Relying on truthiness when 0 is a valid value
if (price) { showPrice(price); } hides the price of free items that cost 0. To ask "is there a value?", write a precise check such as price !== undefined or price !== null.
4. Putting a semicolon after the condition
In if (stock > 0); { sell(); } the ; becomes the if's empty statement, and the { sell(); } block runs every time regardless of the condition. Put the { straight after the ).
Best practices
Best practices
- Test every boundary of a chain before trusting it: just below, exactly on, and just above each limit.
- Handle rare or error cases first and the normal path last, so the main logic is not buried in nesting.
- Name complex conditions: after const canCheckout = isLoggedIn && cartItems > 0;, if (canCheckout) reads like a sentence.
Mini challenge
Mini challenge: a grade calculator
Write an if / else if chain that turns a score into a grade, and test it with five scores.
- Return "Invalid" for scores below 0 or above 100
- 80 and above is "A", 65-79 is "B", 50-64 is "C", anything else is "F"
- Order the conditions so no branch hides another
- Print the score and grade for 95, 72, 50, 12 and 105
function gradeFor(score) {
// TODO: "Invalid" when score is below 0 or above 100
// TODO: "A" for 80+, "B" for 65-79, "C" for 50-64
// TODO: otherwise "F"
}
// TODO: print each score next to its grade: 95, 72, 50, 12, 105Expected: Five lines are printed: 95 A 72 B 50 C 12 F 105 Invalid
Show hint
The function wrapper only lets you test several scores (functions get their own lesson, lesson 11); you fill in the if chain. Put the Invalid check first, then test score >= 80, score >= 65 and score >= 50 in that order.
Show solution
function gradeFor(score) {
if (score < 0 || score > 100) {
return "Invalid";
} else if (score >= 80) {
return "A";
} else if (score >= 65) {
return "B";
} else if (score >= 50) {
return "C";
} else {
return "F";
}
}
console.log(95, gradeFor(95));
console.log(72, gradeFor(72));
console.log(50, gradeFor(50));
console.log(12, gradeFor(12));
console.log(105, gradeFor(105));Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- An if / else if / else chain is tested from the top, and only the first true branch runs.
- Everything is truthy except the eight falsy values: false, 0, -0, 0n, "", null, undefined and NaN.
- Order range conditions from the narrowest, always use braces, and compare with ===.
- Use if for actions and condition ? a : b for choosing a value.
MDN — JavaScript Guide — MDN Web Docs