JavaScript Tutorial
Learn how to handle both true and false conditions with if...else statements. Master binary decision-making in JavaScript.
Why this matters
Real-world applications rarely have simple yes/no decisions. if...else statements allow you to handle both outcomes gracefully.
What is an if...else Statement?
The if...else statement extends the basic if statement by providing an alternative code path to execute when the condition is false.
This allows you to handle both possible outcomes of a condition, making your code more robust and complete.
Basic if...else Statement
let age = 16;
if (age >= 18) {
console.log("You can vote!");
} else {
console.log("You are not old enough to vote.");
}
If the condition is true, the first block executes. If false, the else block executes.
if...else Syntax
The syntax combines the if statement with an else clause. Only one of the two code blocks will execute.
This is perfect for binary decisions where you have exactly two possible outcomes.
if...else Structure
if (condition) {
// code to execute if condition is true
} else {
// code to execute if condition is false
}
The else block executes only when the if condition evaluates to false.
Real-World Examples
if...else statements are commonly used for validation, authentication, and decision-making scenarios.
User Authentication
function checkAccess(user) {
if (user.isLoggedIn && user.role === 'admin') {
return "Access granted to admin panel";
} else {
return "Access denied";
}
}
let currentUser = { isLoggedIn: false, role: 'user' };
console.log(checkAccess(currentUser)); // "Access denied"
Check user permissions and provide appropriate access control.
Form Validation
function validatePassword(password) {
if (password.length >= 8) {
return "Password is strong";
} else {
return "Password must be at least 8 characters";
}
}
console.log(validatePassword("pass123")); // "Password must be at least 8 characters"
console.log(validatePassword("password123")); // "Password is strong"
Validate input and provide feedback based on the validation result.
Even/Odd Number Check
function checkNumber(num) {
if (num % 2 === 0) {
return num + " is even";
} else {
return num + " is odd";
}
}
console.log(checkNumber(4)); // "4 is even"
console.log(checkNumber(7)); // "7 is odd"
Simple mathematical decision based on number properties.
Comparison with if Statement Alone
While if statements handle one case, if...else handles both possible outcomes explicitly.
This makes your code more predictable and easier to understand.
if vs if...else
// Using only if (incomplete logic)
let temperature = 15;
if (temperature > 20) {
console.log("It's warm outside");
}
// What happens when temperature <= 20? Nothing!
// Using if...else (complete logic)
if (temperature > 20) {
console.log("It's warm outside");
} else {
console.log("It's cool outside");
}
if...else ensures you handle both possible outcomes of the condition.
Best Practices
Use if...else when you have exactly two mutually exclusive outcomes to handle.
- Keep both code blocks simple and focused
- Use early returns when possible to avoid else blocks
- Consider ternary operator for simple assignments
- Add comments for complex business logic
- Test both true and false conditions
Ternary Operator Alternative
// Instead of:
let message;
if (age >= 18) {
message = "Adult";
} else {
message = "Minor";
}
// You can use:
let message = age >= 18 ? "Adult" : "Minor";
For simple assignments, the ternary operator provides a more concise alternative.
Early Return Pattern
function getUserStatus(user) {
if (!user) {
return "User not found";
}
// No else needed - function already returned
return user.isActive ? "Active" : "Inactive";
}
Early returns can eliminate the need for else blocks entirely.
Common Mistakes
- Forgetting the else block: Ensure you handle both true and false cases, or use early returns.
- Deep nesting of if...else: Consider else if chains or switch statements for multiple conditions.
- Using else when conditions aren't mutually exclusive: Use separate if statements if both conditions could be true.
Frequently Asked Questions
When should I use if...else vs just if?
Use if...else when you need to handle both possible outcomes. Use just if when you only care about one case.
Can I have multiple statements in else block?
Yes, you can have as many statements as needed in both if and else blocks.
What's the difference between else if and multiple if statements?
else if creates mutually exclusive conditions, while multiple if statements can all execute if conditions overlap.
Related Topics