How to Write If Else Statements in JS: Full Guide
Learn how to write if else statements in JavaScript with real-world examples. Covers two-way branching, nested conditions, code style patterns, and common beginner mistakes.
A plain if statement handles one outcome: something happens when a condition is true, and nothing happens when it is false. Real programs rarely work that way. When a user submits a login form, you need to show the dashboard if the credentials are correct and display an error message if they are not. When a shopping cart calculates shipping, free shipping applies if the total exceeds $50, and standard rates apply if it does not. The if else statement gives you two-way branching: one path for true and another path for false.
This guide covers the full if else syntax, practical patterns for real applications, how to handle nested conditions without creating unreadable code, and the mistakes that cause the most bugs in beginner codebases.
Basic If Else Syntax
The if else statement extends the basic if statement with a second code block that runs when the condition is false:
if (condition) {
// Runs when condition is true
} else {
// Runs when condition is false
}Exactly one of the two blocks always executes. JavaScript evaluates the condition, runs the matching block, and skips the other:
const score = 72;
if (score >= 60) {
console.log("You passed the exam.");
} else {
console.log("You failed the exam. Please retake.");
}
// Output: "You passed the exam."const temperature = 15;
if (temperature > 25) {
console.log("Wear light clothing.");
} else {
console.log("Bring a jacket.");
}
// Output: "Bring a jacket."How the Else Block Works
The else keyword does not have its own condition. It catches everything that the if condition did not. Think of it as the "otherwise" branch:
function checkAccess(user) {
if (user.isAuthenticated) {
return { page: "dashboard", message: "Welcome back" };
} else {
return { page: "login", message: "Please sign in" };
}
}
const loggedIn = checkAccess({ isAuthenticated: true });
console.log(loggedIn); // { page: "dashboard", message: "Welcome back" }
const guest = checkAccess({ isAuthenticated: false });
console.log(guest); // { page: "login", message: "Please sign in" }Since the else block runs for every falsy value, be aware of what JavaScript considers falsy. A condition like if (user.name) enters the else block when user.name is "" (empty string), null, or undefined, because all three are falsy:
function greetUser(name) {
if (name) {
console.log(`Hello, ${name}!`);
} else {
console.log("Hello, anonymous user!");
}
}
greetUser("Ada"); // "Hello, Ada!"
greetUser(""); // "Hello, anonymous user!" (empty string is falsy)
greetUser(null); // "Hello, anonymous user!" (null is falsy)
greetUser(undefined); // "Hello, anonymous user!" (undefined is falsy)Real-World If Else Patterns
Form Validation with User Feedback
function validatePassword(password) {
if (password.length >= 8) {
const hasUppercase = /[A-Z]/.test(password);
const hasNumber = /\d/.test(password);
if (hasUppercase && hasNumber) {
return { valid: true, strength: "strong" };
} else {
return { valid: true, strength: "weak", hint: "Add uppercase and numbers" };
}
} else {
return { valid: false, error: "Password must be at least 8 characters" };
}
}
console.log(validatePassword("hello")); // { valid: false, error: "..." }
console.log(validatePassword("helloworld")); // { valid: true, strength: "weak", ... }
console.log(validatePassword("Hello1world")); // { valid: true, strength: "strong" }Toggling UI State
function toggleTheme(currentTheme) {
if (currentTheme === "dark") {
document.body.classList.remove("dark");
localStorage.setItem("theme", "light");
return "light";
} else {
document.body.classList.add("dark");
localStorage.setItem("theme", "dark");
return "dark";
}
}Handling API Responses
async function fetchUserProfile(userId) {
const response = await fetch(`/api/users/${userId}`);
if (response.ok) {
const data = await response.json();
return { success: true, user: data };
} else {
const status = response.status;
if (status === 404) {
return { success: false, error: "User not found" };
} else if (status === 403) {
return { success: false, error: "Access denied" };
} else {
return { success: false, error: `Server error: ${status}` };
}
}
}Calculating Discounts
function calculateDiscount(cartTotal, isMember) {
if (isMember) {
if (cartTotal >= 200) {
return cartTotal * 0.20; // 20% member discount for orders $200+
} else {
return cartTotal * 0.10; // 10% base member discount
}
} else {
if (cartTotal >= 100) {
return cartTotal * 0.05; // 5% non-member discount for orders $100+
} else {
return 0; // No discount
}
}
}
console.log(calculateDiscount(250, true)); // 50 (20%)
console.log(calculateDiscount(80, true)); // 8 (10%)
console.log(calculateDiscount(150, false)); // 7.5 (5%)
console.log(calculateDiscount(50, false)); // 0If Else with Logical Operators
Combine conditions using logical operators to handle complex requirements in a single if else:
function canRentCar(age, hasLicense, hasCreditCard) {
if (age >= 21 && hasLicense && hasCreditCard) {
return "Approved: you can rent a car.";
} else {
const reasons = [];
if (age < 21) reasons.push("Must be 21 or older");
if (!hasLicense) reasons.push("Valid license required");
if (!hasCreditCard) reasons.push("Credit card required");
return `Denied: ${reasons.join(", ")}`;
}
}
console.log(canRentCar(25, true, true)); // "Approved: you can rent a car."
console.log(canRentCar(19, true, false)); // "Denied: Must be 21 or older, Credit card required"Comparison: If Else vs Ternary Operator
For simple two-way assignments, JavaScript offers the ternary operator as a compact alternative:
// If else (verbose but explicit)
let greeting;
if (isLoggedIn) {
greeting = "Welcome back!";
} else {
greeting = "Please log in.";
}
// Ternary operator (compact for simple cases)
const greeting = isLoggedIn ? "Welcome back!" : "Please log in.";| Criteria | If Else | Ternary |
|---|---|---|
| Readability | Clear at any complexity | Best for single expressions |
| Multi-statement blocks | Supported | Not supported |
| Nesting | Works but can get messy | Becomes unreadable quickly |
| Side effects | Natural fit | Awkward, avoid |
| Use case | General branching | Inline assignments, return values |
When to Use Which
Use if else when the branches contain multiple statements, side effects (like logging or DOM updates), or complex logic. Use the ternary operator only for simple, single-expression assignments where both branches return a value.
If Else vs Early Return
When a function checks a condition and the else block contains the "main" logic, you can simplify with an early return:
// With if else
function getDiscount(user) {
if (user.isPremium) {
return 0.15;
} else {
return 0;
}
}
// With early return (cleaner)
function getDiscount(user) {
if (user.isPremium) {
return 0.15;
}
return 0;
}Early returns work especially well when you have multiple conditions to check before the main logic:
function processOrder(order) {
if (!order) {
return { error: "Order is required" };
}
if (order.items.length === 0) {
return { error: "Cart is empty" };
}
if (!order.shippingAddress) {
return { error: "Shipping address required" };
}
// Main logic (no else nesting needed)
const subtotal = order.items.reduce((sum, item) => sum + item.price, 0);
const tax = subtotal * 0.08;
return { total: subtotal + tax, items: order.items.length };
}Best Practices
Writing Clean If Else Logic
These habits produce if else code that is easy to read, test, and maintain.
Put the most common case first. If 90% of users are authenticated, put the authenticated branch in the if and the error handling in the else. This matches the mental model of reading code top-to-bottom: the expected path comes first.
Avoid deep nesting with early returns. Instead of wrapping your main logic inside three nested if else blocks, check for failure conditions and return early. The main logic stays at the top level.
Use consistent formatting. Always put the else keyword on the same line as the closing brace of the if block: } else {. This is the dominant JavaScript style (enforced by Prettier and most ESLint configs).
Do not leave empty else blocks. If the else block has no meaningful code, remove it entirely. An empty else { } adds visual noise without adding behavior.
Extract complex conditions into named variables. Instead of if (user.age >= 18 && user.hasVerifiedEmail && user.accountAge > 30), extract: const isEligible = ... and then use if (isEligible).
Common Mistakes and How to Avoid Them
Frequent If Else Bugs
These patterns cause some of the hardest-to-find bugs in JavaScript conditional logic.
Missing curly braces on multi-line else blocks. Without braces, only the first statement after else is conditional. The second statement runs unconditionally, which creates silent bugs. Always use braces.
Confusing assignment (=) with comparison (===). Writing if (status = "active") assigns the string to status and always evaluates as truthy. Use if (status === "active") for comparison.
Unreachable else blocks. If the if condition always returns true (for example, if (true || someCondition)), the else block never runs. Check your conditions for logical errors.
Forgetting that strings are compared by Unicode value. if ("apple" > "Banana") is true because lowercase letters have higher Unicode values than uppercase. For case-insensitive comparison, convert both sides: if (a.toLowerCase() === b.toLowerCase()).
Nested if else when else if would work. Beginners sometimes write if (a) { } else { if (b) { } else { } } instead of the cleaner if (a) { } else if (b) { } else { }. The else if form is easier to read and equivalent in behavior.
Next Steps
Chain conditions with else if
When two outcomes are not enough, else if lets you test multiple conditions in sequence for multi-way branching.
Explore the [switch statement](/tutorials/programming-languages/javascript/js-switch-statement-vs-if-else-which-is-better)
For comparing a single variable against many possible values, the switch statement provides a structured alternative to long if/else if chains.
Learn the ternary operator
Condense simple if/else assignments into a single inline expression for cleaner, more compact code.
Practice with form validation
Build a registration form validator that uses if/else to check email format, password strength, and age requirements.
Rune AI
Key Insights
- Exactly one block runs: the
ifblock when true, theelseblock when false, never both and never neither - Early returns beat deep nesting: check for failure conditions first and return before the main logic
- Ternary for simple assignments: use the ternary operator for one-line value assignments,
if elsefor everything else - Always use braces and strict equality: consistency prevents the most common conditional logic bugs
Frequently Asked Questions
What is the difference between if and if else in JavaScript?
Can I have multiple else blocks in a single if statement?
Should I always use else after an if statement?
Is there a performance difference between if else and the ternary operator?
How do I handle more than two conditions with if else?
Conclusion
The if else statement is the workhorse of JavaScript conditional logic, handling every situation where your code needs to choose between two paths. Writing clean if else code comes down to three habits: keeping the expected case first, using early returns instead of deep nesting, and extracting complex conditions into named variables. Once two-way branching feels natural, you are ready to handle multi-way decisions with else if chains.
More in this topic
OffscreenCanvas API in JS for UI Performance
Master the OffscreenCanvas API to offload rendering from the main thread. Covers worker-based 2D and WebGL rendering, animation loops inside workers, bitmap transfer, double buffering, chart rendering pipelines, image processing, and performance measurement strategies.
Advanced Web Workers for High Performance JS
Master Web Workers for truly parallel JavaScript execution. Covers dedicated and shared workers, structured cloning, transferable objects, SharedArrayBuffer with Atomics, worker pools, task scheduling, Comlink RPC patterns, module workers, and performance profiling strategies.
JavaScript Macros and Abstract Code Generation
Master JavaScript code generation techniques for compile-time and runtime metaprogramming. Covers AST manipulation, Babel plugin authorship, tagged template literals as macros, code generation pipelines, source-to-source transformation, compile-time evaluation, and safe eval alternatives.