The else Clause
What you'll learn: How to execute alternative code when an if condition evaluates to false.
The Need for Alternatives
You've learned that the if statement lets you run code only when a condition is true. But what happens when the condition is false? Often, you want to do something else instead. That's exactly what the else clause provides—a fallback path for when your condition doesn't hold.
Think of it like a fork in the road: if the weather is sunny, take the beach path; else (otherwise), take the museum path. The else ensures you always take one path or the other.
How It Works
The else clause attaches directly to an if statement. If the Boolean expression in the if evaluates to false, the program skips the if block and executes the else block instead:
if (temperature > 30) {
print("It's hot outside")
} else {
print("It's not hot outside")
}
In this example, one of the two messages will always print. If temperature is 35, you see "It's hot outside." If temperature is 20, you see "It's not hot outside." The else provides an explicit action for the false case.
When to Use else
Use else when you have two mutually exclusive paths: one for when the condition is true, another for when it's false. It makes your logic clear and ensures both cases are handled explicitly.
Key Takeaway: The else clause provides an alternative code path that executes when the if condition is false, ensuring you handle both outcomes explicitly.