The Else Clause
You'll learn how to provide alternative code paths when an if condition fails.
What Is the Else Clause?
The else clause lets you specify what should happen when your if condition evaluates to false. It's like a backup plan—if the first condition doesn't work out, JavaScript follows the alternative route instead.
Think of it like a fork in the road: if says "go left if it's sunny," while else says "otherwise, go right." Only one path executes, never both.
Syntax
if (condition) {
// Runs when condition is true
} else {
// Runs when condition is false
}
The else block immediately follows the closing brace of the if block. No condition is needed after else—it catches everything that didn't match the if.
Examples
let age = 15;
if (age >= 18) {
console.log("You can vote");
} else {
console.log("You cannot vote yet");
}
// Logs: "You cannot vote yet"
let isRaining = false;
if (isRaining) {
console.log("Take an umbrella");
} else {
console.log("Enjoy the sunshine");
}
// Logs: "Enjoy the sunshine"
Without else, you'd need two separate if statements checking opposite conditions. The else clause is cleaner and guarantees exactly one path executes.
When to Use Else
Use else when you have a clear binary choice: one thing should happen when the condition is true, and something different should happen when it's false. If nothing should happen in the false case, you don't need else.
Key Takeaway: The else clause provides an alternative execution path that runs only when the if condition is false, ensuring one of two code blocks executes.