Conditionals
Objectives
By the end of this chapter, you should be able to:
- Branch code with
if,else if, andelse - Use the
===operator to write clear conditions - Choose between several fixed options with
switch - Explain why every
casein aswitchneeds abreak
💡 Why this matters: Almost nothing a real program does happens unconditionally. It shows a message only if a form is invalid, gives a discount only if a cart total is high enough, greets a returning user differently than a new one. Conditionals are how you write “only if.”
The if Statement
An if statement runs a block of code only when a condition is true.
const age = 20;
if (age >= 18) {
console.log("You can vote.");
}
// You can vote.
The condition goes inside the parentheses, and it’s usually built with a comparison operator like ===, >, or >= from Module 2. If the condition evaluates to false, the block is skipped entirely and nothing happens.
const age = 15;
if (age >= 18) {
console.log("You can vote.");
}
// (nothing is printed)
else: Running Code When the Condition Is False
else gives you a block to run when the if condition is false.
const age = 15;
if (age >= 18) {
console.log("You can vote.");
} else {
console.log("You cannot vote yet.");
}
// You cannot vote yet.
Exactly one of the two blocks runs, never both, and never neither.
else if: Checking Several Conditions in Order
When you have more than two possibilities, chain else if blocks between if and else. JavaScript checks each condition top to bottom and runs the first block whose condition is true, then skips the rest.
const score = 72;
if (score >= 90) {
console.log("Grade: A");
} else if (score >= 80) {
console.log("Grade: B");
} else if (score >= 70) {
console.log("Grade: C");
} else {
console.log("Grade: F");
}
// Grade: C
score is 72. JavaScript checks score >= 90 (false), then score >= 80 (false), then score >= 70 (true), runs that block, and stops. It never checks the final else. Order matters here: if you wrote score >= 70 before score >= 80, every score of 80 or higher would incorrectly land in the “C” bucket, because the first matching condition wins.
Use === (not ==) when a condition checks for equality, exactly like Module 2 covered for comparisons:
const name = "Maya";
if (name === "Maya") {
console.log("Welcome back, Maya.");
} else {
console.log("Welcome, guest.");
}
// Welcome back, Maya.
The switch Statement
When you’re comparing one value against several fixed options, a switch statement can read more clearly than a long else if chain.
const day = "Tuesday";
switch (day) {
case "Monday":
console.log("Start of the work week.");
break;
case "Tuesday":
console.log("Second day.");
break;
case "Friday":
console.log("Almost the weekend.");
break;
default:
console.log("Just another day.");
}
// Second day.
switch compares day against each case value using the same strict equality as ===. When it finds a match, it runs the code under that case. default runs if nothing else matched, similar to a final else.
Why break Matters: A Fall-Through Bug
Here’s the part that trips people up: without break, JavaScript doesn’t stop at the matching case. It keeps running every case below it too, whether their labels match or not. This is called “fall-through.” Watch what happens when the break statements are missing:
const day = "Monday";
switch (day) {
case "Monday":
console.log("Start of the work week.");
case "Tuesday":
console.log("Second day.");
case "Friday":
console.log("Almost the weekend.");
default:
console.log("Just another day.");
}
// Start of the work week.
// Second day.
// Almost the weekend.
// Just another day.
day is "Monday", so execution starts at the "Monday" case. But with no break to stop it, it just keeps falling into "Tuesday", then "Friday", then default, printing all four lines instead of one. This is almost never what you want.
Adding break back fixes it, because break exits the switch entirely as soon as its block finishes:
const day = "Monday";
switch (day) {
case "Monday":
console.log("Start of the work week.");
break;
case "Tuesday":
console.log("Second day.");
break;
case "Friday":
console.log("Almost the weekend.");
break;
default:
console.log("Just another day.");
}
// Start of the work week.
The rule: put break at the end of every case unless you deliberately want fall-through (rare, and worth a comment explaining why if you ever do it). The default case doesn’t strictly need a trailing break since there’s nothing left to fall into, but adding one is a safe habit if you ever add more cases below it later.
Try It
Run each of these and check the output against what you’d expect before running it.
- Write an
if/elsethat checks a variabletemperature. If it’s30or above, log"Hot". Otherwise, log"Not hot". - Write an
if/else if/elsechain for a variablehour(0 to 23): log"Morning"ifhour < 12,"Afternoon"ifhour < 18, otherwise"Evening". - Write a
switchon a variablefruitwith cases"apple","banana", and adefault, each logging a different message. Remove onebreakon purpose and confirm you see fall-through, then put it back.
Recap
ifruns a block only when its condition istrue;elseruns when it’sfalse.else ifchains check conditions in order and stop at the first match, so order matters.switchcompares one value against several fixed options using strict equality.- Without
break, aswitchfalls through into every case below the match. Always addbreakunless you have a specific reason not to.
Next lesson: repeating code with for, while, and do...while loops.