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.

JavaScriptbeginner
11 min read

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:

javascriptjavascript
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:

javascriptjavascript
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."
javascriptjavascript
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:

javascriptjavascript
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:

javascriptjavascript
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

javascriptjavascript
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

javascriptjavascript
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

javascriptjavascript
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

javascriptjavascript
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));   // 0

If Else with Logical Operators

Combine conditions using logical operators to handle complex requirements in a single if else:

javascriptjavascript
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:

javascriptjavascript
// 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.";
CriteriaIf ElseTernary
ReadabilityClear at any complexityBest for single expressions
Multi-statement blocksSupportedNot supported
NestingWorks but can get messyBecomes unreadable quickly
Side effectsNatural fitAwkward, avoid
Use caseGeneral branchingInline 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:

javascriptjavascript
// 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:

javascriptjavascript
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

Rune AI

Key Insights

  • Exactly one block runs: the if block when true, the else block 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 else for everything else
  • Always use braces and strict equality: consistency prevents the most common conditional logic bugs
RunePowered by Rune AI

Frequently Asked Questions

What is the difference between if and if else in JavaScript?

plain `if` statement executes code only when the condition is true and does nothing when it is false. An `if else` statement provides a second code block that runs exclusively when the condition is false. Use `if` alone when nothing needs to happen for the false case; use `if else` when both outcomes require distinct actions.

Can I have multiple else blocks in a single if statement?

No. Each `if` can have at most one `else` block. If you need more than two branches, use `else if` to chain additional conditions between the `if` and the final `else`. The final `else` acts as the default case when none of the previous conditions matched.

Should I always use else after an if statement?

No. Use `else` only when the false case needs its own logic. If the `if` block handles the edge case and the main logic continues after it (like a guard clause), an `else` block adds unnecessary nesting. Omit it and let the code flow naturally after the `if` block.

Is there a performance difference between if else and the ternary operator?

No meaningful difference. Both compile to equivalent branch logic. Modern [JavaScript engine](/tutorials/programming-languages/javascript/what-is-a-javascript-engine-a-complete-guide)s optimize both patterns identically. Choose based on readability: use `if else` for complex branching with multiple statements, and the ternary operator for simple inline assignments or return expressions.

How do I handle more than two conditions with if else?

Use the `else if` syntax to chain additional conditions. Write `if (condition1) { } else if (condition2) { } else if (condition3) { } else { }`. JavaScript evaluates each condition from top to bottom and executes the first matching block. The final `else` is optional and handles any case not covered by the preceding conditions.

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.