If, Else If and Else
The if statement runs a block of code only when a condition is true. Add else to run another block when it is false, and else if to test more conditions in order. Every rule in the Fee Tracker, from "charge a late fee after ten days" to "show a thank-you note when the balance reaches zero", is an if statement.
In One Minute
if (condition) { ... }runs the block when the condition is truthy.else { ... }runs when it isn't;else if (other) { ... }tests another condition.- JavaScript checks the conditions top to bottom and stops at the first true one, so order matters.
- Always use braces, even for one line.
- Prefer early returns (guard clauses) to deep nesting.
The if Statement
Syntax
if (condition) {
// runs when condition is truthy
} else if (otherCondition) {
// runs when condition is falsy and otherCondition is truthy
} else {
// runs when no condition above was truthy
}The condition goes in parentheses. It is usually a comparison, but any value works: JavaScript converts it to a boolean using the truthy and falsy rules (next lesson).
Example
const balance = 45;
if (balance > 0) {
console.log(`Balance due: $${balance}`);
}
if (balance === 0) {
console.log("Paid in full. Thank you!");
} else {
console.log("Please pay before the due date.");
}Balance due: $45
Please pay before the due date.else if Chains
Use else if to choose one path from several. JavaScript tests each condition in order and runs only the first block whose condition is true:
function lateStatus(daysLate) {
if (daysLate <= 0) {
return "On time";
} else if (daysLate <= 10) {
return "Grace period";
} else if (daysLate <= 30) {
return "Late fee applies";
} else {
return "Sent to the office";
}
}
console.log(lateStatus(0));
console.log(lateStatus(7));
console.log(lateStatus(18));
console.log(lateStatus(45));On time
Grace period
Late fee applies
Sent to the officeNesting and Guard Clauses
An if can contain another if. A little nesting is fine, but several levels make code hard to follow (people call it the "arrow shape", because the indentation pushes code to the right).
A guard clause checks for a case that ends the work early and returns immediately. The main logic then stays at the left edge:
function lateFee(record) {
if (!record) return 0;
if (record.waived) return 0;
if (record.daysLate <= 10) return 0;
const fee = record.daysLate * 2;
return fee > 30 ? 30 : fee;
}
console.log(lateFee({ daysLate: 18, waived: false }));
console.log(lateFee({ daysLate: 18, waived: true }));
console.log(lateFee(null));function lateFee(record) {
if (record) {
if (!record.waived) {
if (record.daysLate > 10) {
const fee = record.daysLate * 2;
if (fee > 30) {
return 30;
} else {
return fee;
}
}
}
}
return 0;
}30
0
0Both versions do the same thing. In the first, each special case is dealt with and forgotten in one line, and the real calculation is easy to find.
Braces and One-Line if
JavaScript allows an if without braces when the body is one statement: if (isPaid) sendReceipt();. The danger appears when someone adds a second line later:
const isPaid = false;
if (isPaid)
console.log("Sending receipt");
console.log("Marking as closed");Marking as closedExplanation: only the first line belongs to the if. The indentation of the second line is misleading; it runs every time, and the unpaid record is "closed". With braces, this bug can't happen.
In Practice
The Fee Tracker decides which message to show at the top of a student's page. Guard clauses handle missing data first; an else if chain picks the message:
function banner(student) {
if (!student) return "No student selected.";
const { name, balance, daysLate } = student;
if (balance <= 0) {
return `${name} is paid in full.`;
} else if (daysLate > 10) {
return `${name} is ${daysLate} days late with $${balance} due.`;
} else {
return `${name} has $${balance} due.`;
}
}
console.log(banner({ name: "Navika", balance: 0, daysLate: 0 }));
console.log(banner({ name: "Srihitha", balance: 120, daysLate: 14 }));
console.log(banner({ name: "Advitha", balance: 60, daysLate: 2 }));
console.log(banner(undefined));Navika is paid in full.
Srihitha is 14 days late with $120 due.
Advitha has $60 due.
No student selected.The line const { name, balance, daysLate } = student; copies three properties into variables at once. It is called destructuring, and it has its own lesson in the arrays chapter.
Common Mistakes
Using = in a condition. if (balance = 0) assigns 0, and since 0 is falsy, the block never runs. Use ===.
Wrong order in an else if chain. A broad condition early catches cases meant for later branches. Put the narrowest conditions first.
A semicolon after the condition. if (isPaid); { sendReceipt(); } ends the if at the semicolon, and the block always runs.
Testing a number with truthiness by accident. if (balance) is false for a balance of 0, which might be exactly the case you wanted to handle. Compare explicitly: if (balance > 0).
Practice
Challenge: Write gradeBand(grade) that returns "Elementary" for grades 1 to 5, "Middle" for 6 to 8, "High" for 9 to 12, and "Unknown" for anything else, using guard clauses or an else if chain.
Show solution
function gradeBand(grade) {
if (grade < 1 || grade > 12) return "Unknown";
if (grade <= 5) return "Elementary";
if (grade <= 8) return "Middle";
return "High";
}
console.log(gradeBand(3));
console.log(gradeBand(7));
console.log(gradeBand(11));
console.log(gradeBand(15));Elementary
Middle
High
UnknownKey Takeaways
| Pattern | Use it for |
|---|---|
if { } | Do something only sometimes |
if { } else { } | Choose between two paths |
if / else if / else | Choose one of several paths |
if (bad) return; | Leave early on special cases |
Was this tutorial helpful?