The if Statement
An if statement runs a block of code only when a condition is true, which is how a program makes its first decision.
if runs a block when its condition is true, else covers everything else, and else if chains alternatives. Only the first matching branch runs, and the braces decide what belongs to the decision.
EXERCISE
1Running Code Only When Something Is True
An if statement takes a condition and a block, and runs the block only when the condition works out to true.
Everything you have written so far runs top to bottom, every line, every time. if is the first tool that lets a program choose.
The shape of it:
if (age >= 18) {
console.log("You can vote");
}
// ^condition^ ^-- the block, which runs only when true
A condition is anything that produces true or false:
const age = 20;
const name = "Ada";
if (age >= 18) {
console.log("Adult"); // runs
}
if (name === "Ada") {
console.log("Hello Ada"); // runs
}
if (age > 100) {
console.log("Centenarian"); // does not run
}
The braces decide what belongs to the decision:
const loggedIn = false;
if (loggedIn) {
console.log("Welcome back"); // skipped
console.log("Loading feed"); // skipped
}
console.log("Page ready"); // always runs
// Without braces, only ONE line belongs to the if:
if (loggedIn)
console.log("Welcome back"); // skipped
console.log("Loading feed"); // ALWAYS RUNS, and the indentation lies
Pro Tip: Always write the braces, even for a single line. The version without them is legal and reads as though two lines are guarded when only one is, which is a bug that survives code review because the indentation looks correct. This exact mistake caused a famous security flaw in Apple's TLS code in 2014.
EXERCISE
2else and else if
One condition gives you two paths, and chaining conditions lets a program choose between as many alternatives as you need.
else covers everything the if did not:
const age = 15;
if (age >= 18) {
console.log("Adult");
} else {
console.log("Minor"); // this runs
}
// Exactly one of the two blocks runs. Always one, never both.
else if adds more alternatives:
const score = 72;
if (score >= 90) {
console.log("A");
} else if (score >= 75) {
console.log("B");
} else if (score >= 60) {
console.log("C"); // this runs
} else {
console.log("Fail");
}
Order matters, because the first match wins:
const score = 95;
// Wrong order: every score above 60 matches the first test
if (score >= 60) {
console.log("C"); // 95 lands here and stops
} else if (score >= 90) {
console.log("A"); // unreachable for any score
}
// Correct order: narrowest condition first
if (score >= 90) {
console.log("A"); // 95 lands here
} else if (score >= 60) {
console.log("C");
}
Separate ifs are not the same as else if:
const n = 5;
if (n > 0) console.log("positive");
if (n > 3) console.log("above three");
// Both print. Each if is judged on its own.
if (n > 0) console.log("positive");
else if (n > 3) console.log("above three");
// Only "positive" prints. The chain stopped at the first match.
An else if chain is a single decision with several outcomes, and a run of separate if statements is several independent decisions. Choosing the wrong one gives you either two messages where you wanted one, or one where you wanted two. Ask whether the cases exclude each other, and let that pick the shape.
EXERCISE
3Guard Clauses, and Keeping Code Flat
Deeply nested if statements are hard to follow, and returning early is the standard way to keep decisions readable.
Nesting works. It also drifts rightwards fast, and the real logic ends up buried.
The nested version:
function checkout(user, cart) {
if (user) {
if (user.isVerified) {
if (cart.items.length > 0) {
return "Order placed";
} else {
return "Cart is empty";
}
} else {
return "Please verify your email";
}
} else {
return "Please log in";
}
}
The same logic, written as guards:
function checkout(user, cart) {
if (!user) return "Please log in";
if (!user.isVerified) return "Please verify your email";
if (cart.items.length === 0) return "Cart is empty";
return "Order placed";
}
console.log(checkout(null, {})); // Please log in
Every failure case is handled and dismissed at the top, and the last line is the thing the function is actually for.
The same idea without a function, using continue in a loop:
const users = [{ age: 20 }, { age: 15 }, { age: 30 }];
for (const user of users) {
if (user.age < 18) continue; // skip this one, move on
console.log(`Serving user aged ${user.age}`);
}
// Serving user aged 20
// Serving user aged 30
Pro Tip: Handle the exceptional cases first and get them out of the way, so the main path of your code sits at the left margin where it is easy to find. A reader should be able to scan the last few lines of a function and see what it does, without tracing which of four nested branches they are in.
