Programming If Statements- Code Examples and Best Practices
What If Statements Actually Do
An if statement is the most basic decision-making tool in programming. It checks a condition. If the condition is true, it runs a block of code. If not, it skips that block.
That's it. No magic, no complexity. But how you write them determines whether your code is readable or a nightmare someone will have to untangle at 2 AM.
The Basic Syntax Across Languages
Every mainstream language has if statements. The logic is identical. The syntax changes slightly.
Python
if condition:
# run this code
Python uses indentation to define the code block. No braces, no keywords needed to close the block.
JavaScript
if (condition) {
// run this code
}
JavaScript wraps the condition in parentheses and uses curly braces to define the block.
Java / C / C++
if (condition) {
// run this code
}
Same structure as JavaScript. These languages are basically identical for basic if statements.
C#
if (condition)
{
// run this code
}
C# allows the brace on a new line. Style preference, but it works either way.
If-Else: When You Need a Fallback
Sometimes you need to run code when the condition is false too. That's what else is for.
if (user.isLoggedIn) {
showDashboard();
} else {
showLoginForm();
}
The else block runs only when the if condition evaluates to false. Simple.
If-Else If-Else: Multiple Conditions
Need to check several conditions in sequence? Use else if.
if (score >= 90) {
grade = "A";
} else if (score >= 80) {
grade = "B";
} else if (score >= 70) {
grade = "C";
} else {
grade = "F";
}
The first condition that evaluates to true runs its block. The rest are skipped. Order matters here.
Ternary Operator: One-Liner Decisions
For simple assignments, a ternary operator is cleaner than a full if-else block.
// Instead of this:
if (isLoggedIn) {
message = "Welcome back";
} else {
message = "Please sign in";
}
// Do this:
message = isLoggedIn ? "Welcome back" : "Please sign in";
The syntax is condition ? valueIfTrue : valueIfFalse. Use it for simple assignments. Don't nest ternaries—it gets unreadable fast.
Nesting If Statements: When It's Wrong
You can nest if statements. You shouldn't do it excessively.
// Don't do this:
if (user != null) {
if (user.isActive) {
if (user.hasSubscription) {
// finally do something
}
}
}
This is called the "arrow anti-pattern" or "pyramid of doom." It makes code hard to read and harder to debug.
Instead, use early returns or combine conditions:
if (user == null || !user.isActive || !user.hasSubscription) {
return; // handle error cases first
}
// now you have a valid user, proceed
Combining Conditions: AND, OR, NOT
You rarely check just one thing. Real conditions combine multiple checks.
AND (&&)
Both conditions must be true.
if (user.age >= 18 && user.hasLicense) {
allowAccess();
}
OR (||)
At least one condition must be true.
if (user.isAdmin || user.isOwner) {
showAdminPanel();
}
NOT (!)
Inverts the condition.
if (!user.isBanned) {
allowAccess();
}
Complex Combinations
if ((isWeekend || isHoliday) && !isMaintenanceMode) {
showSpecialOffers();
}
Use parentheses to make the logic explicit. Don't rely on operator precedence—it's easy to get wrong and hard to read.
Common Mistakes to Avoid
- Using == for object comparison. In languages like JavaScript, use === to avoid type coercion bugs.
- Forgetting braces for multi-line blocks. Looks fine until you add a second line and only the first executes.
- Checking the wrong condition order. Put the most common case first for better performance in some languages.
- Over-complicated boolean logic. If your condition takes more than a line to read, extract it to a variable with a clear name.
Comparing If vs Switch vs Pattern Matching
Multiple conditions can be handled different ways. Here's how they stack up.
| Feature | If-Else Chain | Switch Statement | Pattern Matching |
|---|---|---|---|
| Readability | Good for 2-3 conditions | Good for many discrete values | Excellent for type-based checks |
| Flexibility | Any condition type | Equality checks only | Complex conditions supported |
| Performance | Evaluates sequentially | May optimize to jump table | Varies by language |
| Best For | Range checks, complex logic | Menu-style selections | Type checking, destructuring |
How to Write Clean If Statements
1. Use Descriptive Condition Variables
// Bad
if (user.account.balance > 100 && user.account.status === "active") {
// Good
boolean hasSufficientBalance = user.account.balance > 100;
boolean isAccountActive = user.account.status.equals("active");
if (hasSufficientBalance && isAccountActive) {
}
2. Keep the Positive Case First
// Bad
if (!isNotFound) {
// handle error
} else {
// handle success
}
// Good
if (isFound) {
// handle success
} else {
// handle error
}
3. Extract Complex Conditions to Methods
// Bad
if (user.age >= 18 && user.country.equals("US") && !user.isRestricted) {
// Good
if (userMeetsRequirements(user)) {
// ...
}
private boolean userMeetsRequirements(User user) {
return user.age >= 18
&& user.country.equals("US")
&& !user.isRestricted;
}
4. Use Early Returns to Reduce Nesting
// Bad - nested structure
function processOrder(order) {
if (order != null) {
if (order.items.length > 0) {
if (isValidCustomer(order.customer)) {
// finally do something
}
}
}
}
// Good - early returns
function processOrder(order) {
if (order == null) return;
if (order.items.isEmpty()) return;
if (!isValidCustomer(order.customer)) return;
// do the actual work
}
Getting Started: Your First If Statement
Here's a complete example in JavaScript. It checks a user's age and returns whether they can access content.
function canAccessContent(userAge, contentRating) {
// Define age thresholds
const MINIMUM_AGE = 13;
const TEEN_AGE = 17;
// Check if content is mature
const isMature = contentRating === "R" || contentRating === "X";
// Under minimum age - no access
if (userAge < MINIMUM_AGE) {
return { allowed: false, reason: "Too young" };
}
// Under teen age - no mature content
if (userAge < TEEN_AGE && isMature) {
return { allowed: false, reason: "Age restricted" };
}
// All checks passed
return { allowed: true, reason: "Access granted" };
}
// Test it
console.log(canAccessContent(12, "PG")); // { allowed: false, reason: "Too young" }
console.log(canAccessContent(16, "R")); // { allowed: false, reason: "Age restricted" }
console.log(canAccessContent(20, "R")); // { allowed: true, reason: "Access granted" }
This example shows early returns, combined conditions, and clear variable naming. That's the standard for production code.
When to Use What
- Simple true/false check → Basic if statement
- Assign one of two values → Ternary operator
- Two exclusive paths → if-else
- Multiple exclusive conditions → if-else if-else or switch
- Complex boolean logic → Extract to named variables or methods
The Bottom Line
If statements are not complicated. The mistakes people make are always about readability, not logic.
Keep conditions simple. Use early returns. Name your boolean variables. If a condition is hard to read at a glance, refactor it before moving on.
Your future self will thank you. So will the developer who inherits your code.