How to Write JavaScript if else Statements with Examples

Making decisions is very important in programming, and JavaScript conditional operators are your primary tools for implementing this decision-making logic. From basic if statement examples to complex nested conditional statements, this guide covers everything you need to write clean, efficient, and maintainable code.

Whether you’re a complete beginner learning about JavaScript basics or an experienced developer looking to refine your understanding of JavaScript control structures, you’ll find valuable insights and practical examples in this guide. We’ll explore how to use conditional logic in JavaScript for real-world scenarios like form validation, user authentication, and dynamic content rendering.

Understanding Conditional Logic

At its core, conditional logic in JavaScript evaluates whether a condition is true or false and executes different code blocks accordingly. Think of it as your program making decisions, much like how we make decisions in daily life.

Consider this real-world scenario: When you wake up in the morning, you might think:

// Real-world decision making
if (isRaining) {
    takeUmbrella();
} else {
    wearSunglasses();
}

The Building Blocks of Conditions

Before diving into if-else statements, let’s understand the components that make up conditions:

  1. Comparison Operators:
// Equal to (==)
let age = 18;
if (age == 18) {
    console.log("You're exactly 18!");
}

// Strictly equal to (===)
let score = "100";
if (score === 100) {
    console.log("This won't run because types don't match");
}

// Greater than (>)
let temperature = 25;
if (temperature > 30) {
    console.log("It's hot outside!");
}

Simple if Statements

The most basic form of conditional logic. It executes code only when a condition is true, like a one-way gate. If the condition isn’t met, the program simply skips the code block and continues. This is perfect for single-choice scenarios, like checking if a user is logged in.

let isLoggedIn = true;

if (isLoggedIn) {
    console.log("Welcome to your dashboard!");
}

Example: Form Validation

function validateEmail(email) {
    if (email.includes('@') && email.includes('.')) {
        return "Email format looks valid";
    }
    return "Please enter a valid email address";
}

// Usage
console.log(validateEmail("user@example.com")); // "Email format looks valid"
console.log(validateEmail("invalid-email")); // "Please enter a valid email address"

if-else Statements

Think of this as a fork in the road – your code will always take one of two paths. When the condition is true, it executes the first block; when false, it executes the else block. This ensures you handle both possible scenarios, like providing different messages for valid and invalid passwords.

function checkAge(age) {
    if (age >= 18) {
        return "You can vote!";
    } else {
        return "You're too young to vote";
    }
}

// Usage
console.log(checkAge(20)); // "You can vote!"
console.log(checkAge(15)); // "You're too young to vote"

Example: Shopping Cart Discount

function calculateDiscount(cartTotal) {
    if (cartTotal >= 100) {
        return cartTotal * 0.1; // 10% discount
    } else {
        return 0; // No discount
    }
}

const cart1 = calculateDiscount(150); // Returns 15
const cart2 = calculateDiscount(80);  // Returns 0

else-if Statements

This is like having multiple checkpoints in sequence. The code checks each condition in order until it finds one that’s true, then executes that block and skips the rest. It’s perfect for handling multiple distinct cases, like assigning letter grades based on numerical scores.

function gradeScore(score) {
    if (score >= 90) {
        return 'A';
    } else if (score >= 80) {
        return 'B';
    } else if (score >= 70) {
        return 'C';
    } else if (score >= 60) {
        return 'D';
    } else {
        return 'F';
    }
}

console.log(gradeScore(95)); // 'A'
console.log(gradeScore(82)); // 'B'
console.log(gradeScore(45)); // 'F'

Example: Weather App

function getWeatherAdvice(temperature) {
    if (temperature > 30) {
        return "It's hot! Remember to stay hydrated.";
    } else if (temperature > 20) {
        return "Perfect weather for outdoor activities!";
    } else if (temperature > 10) {
        return "Better take a light jacket.";
    } else {
        return "It's cold! Dress warmly.";
    }
}

console.log(getWeatherAdvice(35)); // "It's hot! Remember to stay hydrated."
console.log(getWeatherAdvice(15)); // "Better take a light jacket."

Nested if-else Statements

These are conditions within conditions, like a decision tree. Each level depends on the previous one being true. While powerful, they should be used sparingly as they can become complex quickly. They’re useful when you need to check multiple dependent conditions, like validating user inputs.

function checkLoginStatus(isLoggedIn, userRole) {
    if (isLoggedIn) {
        if (userRole === 'admin') {
            return "Welcome to the admin dashboard";
        } else if (userRole === 'editor') {
            return "Welcome to the editor portal";
        } else {
            return "Welcome to your user dashboard";
        }
    } else {
        return "Please log in to continue";
    }
}

console.log(checkLoginStatus(true, 'admin')); // "Welcome to the admin dashboard"
console.log(checkLoginStatus(true, 'user')); // "Welcome to your user dashboard"
console.log(checkLoginStatus(false, 'admin')); // "Please log in to continue"

Example: E-commerce Order Processing

function processOrder(order) {
    if (order.items.length > 0) {
        if (order.paymentVerified) {
            if (order.shippingAddress) {
                return "Order processed successfully";
            } else {
                return "Please add shipping address";
            }
        } else {
            return "Payment verification failed";
        }
    } else {
        return "Cart is empty";
    }
}

const order = {
    items: ['book', 'pen'],
    paymentVerified: true,
    shippingAddress: "123 Main St"
};

console.log(processOrder(order)); // "Order processed successfully"

Switch Statement

Think of this as a more elegant way to handle multiple specific values for a single variable. Instead of writing many else-if statements, you can list out all possible cases clearly. It’s especially useful when comparing a single value against multiple fixed options, like handling different menu selections.

switch (dayOfWeek) {
    case 1:
        console.log("Monday");
        break;
    case 2:
        console.log("Tuesday");
        break;
    default:
        console.log("Invalid day");
}

Switch vs if-else

While if-else statements are versatile, sometimes switch statements can be more readable, especially when dealing with multiple specific values.

// Using if-else
function getDayName(dayNumber) {
    if (dayNumber === 1) {
        return "Monday";
    } else if (dayNumber === 2) {
        return "Tuesday";
    } else if (dayNumber === 3) {
        return "Wednesday";
    } // ... and so on
}

// Using switch
function getDayNameSwitch(dayNumber) {
    switch (dayNumber) {
        case 1:
            return "Monday";
        case 2:
            return "Tuesday";
        case 3:
            return "Wednesday";
        default:
            return "Invalid day number";
    }
}

Best Practices

1. Use === Instead of ==

When comparing values, strict equality (===) checks both value and type, preventing unexpected behavior. For example, if (5 == "5") evaluates to true with == but false with ===. Always use === unless you specifically need type coercion, which should be rare. Consider this example:

// Less reliable
if (userAge == "21") {  // Works but risky
    allowAccess();
}

// More reliable
if (userAge === 21) {  // Ensures userAge is actually a number
    allowAccess();
}

2. Keep Conditions Simple

Long conditions make code harder to read and maintain. Extract complex conditions into well-named variables or functions that clearly express their purpose. This makes your code self-documenting and easier to update:

// Hard to understand at a glance
if (user.profile.settings.notifications.email && user.profile.settings.notifications.email.frequency === 'daily' && !user.profile.settings.notifications.email.paused) {
    sendEmail();
}

// Clear and maintainable
const canSendDailyEmail = isEmailEnabled(user) && isDailyFrequency(user) && !isEmailPaused(user);
if (canSendDailyEmail) {
    sendEmail();
}

3. Handle Edge Cases First

Placing edge case handling at the beginning of your function (known as “early returns” or “guard clauses”) makes the code’s flow clearer and reduces nesting. This approach validates preconditions before proceeding with the main logic:

function processUserOrder(user, items) {
    // Handle edge cases first
    if (!user) {
        return { error: 'User not found' };
    }

    if (!items || items.length === 0) {
        return { error: 'Cart is empty' };
    }

    if (!user.paymentMethod) {
        return { error: 'No payment method' };
    }

    // Main logic follows - no nesting needed
    return processOrder(user, items);
}

Common Pitfalls

  1. Forgetting Break Statements in Switch
// Bad
switch (fruit) {
    case "apple":
        console.log("Selected apple");
    case "banana":
        console.log("Selected banana");
}

// Good
switch (fruit) {
    case "apple":
        console.log("Selected apple");
        break;
    case "banana":
        console.log("Selected banana");
        break;
}
  1. Complex Nested Conditions
// Bad
if (condition1) {
    if (condition2) {
        if (condition3) {
            // deeply nested code
        }
    }
}

// Good
if (!condition1 || !condition2 || !condition3) return;
// main code here

FAQ

Q: When should I use switch instead of if-else?
A: Use switch when you’re comparing a single variable against multiple specific values. Use if-else for more complex conditions or range comparisons.

Q: How can I avoid deeply nested if statements?
A: Use early returns, combine conditions with logical operators, or break complex logic into smaller functions.

Quick Reference Guide

// Simple if
if (condition) {
    // code
}

// if-else
if (condition) {
    // code
} else {
    // code
}

// else-if
if (condition1) {
    // code
} else if (condition2) {
    // code
} else {
    // code
}

// Nested if
if (condition1) {
    if (condition2) {
        // code
    }
}

// Switch
switch (variable) {
    case value1:
        // code
        break;
    default:
        // code
}

Conclusion

Understanding conditional statements in JavaScript opens up a world of possibilities in your programming journey. These fundamental building blocks allow you to create dynamic, responsive applications that can handle complex decision-making processes. As you’ve learned throughout this guide, each type of conditional statement serves a specific purpose: simple if statements for straightforward checks, if-else for binary decisions, else-if for multiple conditions, and switch statements for comparing specific values.

The key to mastering conditionals lies not just in knowing their syntax, but in understanding when and how to use each type effectively. Remember that while nested conditions offer power and flexibility, they should be used judiciously. The best code is often the simplest code that gets the job done. As you continue to develop your programming skills, focus on writing clean, maintainable conditions that other developers (including your future self) can easily understand.

Previous Article

Learn How to Write Efficient JavaScript Loops for Better Performance

Next Article

Learn JavaScript Comparison and Logical Operators with Examples for Beginners

Write a Comment

Leave a Comment

Your email address will not be published. Required fields are marked *

Subscribe to our Newsletter

Subscribe to our email newsletter to get the latest posts delivered right to your email.
Pure inspiration, zero spam ✨