Writing If else condition in Javascript

As one of the fundamental building blocks of programming, conditional statements allow you to make decisions in your code based on certain criteria. In JavaScript, the if…else condition is often the go-to structure for handling decision-making logic. Whether you are new to coding or brushing up on your JavaScript syntax, understanding how to write and use if…else statements is essential for building dynamic, responsive applications.

TL;DR (Too Long; Didn’t Read)

The if…else condition in JavaScript allows your code to react differently depending on specific conditions. It evaluates a logical expression, runs one block of code if the expression is true, and another if it’s false. You can expand logic further with else if clauses and even nest statements for more granular control. Understanding this structure is crucial for writing logical and efficient JavaScript code.

Understanding the Basic Structure

The if…else condition works by first evaluating a condition. If the condition returns true, the code within the if block is executed. If it returns false and an else statement exists, then the code within the else block is executed instead.

if (condition) {
    // block of code to be executed if the condition is true
} else {
    // block of code to be executed if the condition is false
}

Here’s a simple example:

let age = 20;

if (age >= 18) {
    console.log("You are eligible to vote.");
} else {
    console.log("You are not eligible to vote yet.");
}

In this case, since the age is 20 (which is greater than 18), the output will be You are eligible to vote.

Using else if for Multiple Conditions

Sometimes, two possible outcomes aren’t enough. That’s where the else if statement comes into play. It sits between if and else, and allows for testing additional conditions.

let score = 75;

if (score >= 90) {
    console.log("Grade: A");
} else if (score >= 80) {
    console.log("Grade: B");
} else if (score >= 70) {
    console.log("Grade: C");
} else {
    console.log("Grade: F");
}

This structure will go through each condition until it finds one that evaluates to true. The moment one does, it skips the rest. This prevents unnecessary checks and optimizes performance.

Boolean Logic in Conditions

JavaScript allows the use of boolean operators within if…else statements to create more complex conditions. Commonly used operators include:

  • == (equal to)
  • === (strictly equal to)
  • != (not equal to)
  • && (and)
  • || (or)
  • ! (not)

Here is an example using logical AND (&&):

let age = 25;
let hasID = true;

if (age > 21 && hasID) {
    console.log("Access granted.");
} else {
    console.log("Access denied.");
}

Both conditions must be true for access to be granted. If either one is false, the access will be denied.

Nested if…else Statements

There are situations where you might need to nest an if…else inside another. This is useful when further decisions depend on the result of a preceding condition.

let userLevel = "admin";
let isActive = true;

if (userLevel === "admin") {
    if (isActive) {
        console.log("Admin access granted.");
    } else {
        console.log("Admin account is inactive.");
    }
} else {
    console.log("You are not an admin.");
}

Be careful when nesting too many levels, as it may reduce code readability. In such cases, consider refactoring your code or using switch statements where appropriate.

Avoiding Common Mistakes

When writing if…else statements, keep in mind some common pitfalls:

  • Using = instead of == or ===: The = operator assigns a value, while == and === are used for comparison.
  • Forgetting to use curly braces { }: You can omit braces for single-line blocks, but that can introduce bugs if additional lines are added later.
  • Not understanding truthy and falsy values: JavaScript has a unique way of evaluating values, which can sometimes lead to unexpected results.

For example:

let name = "";

if (name) {
    console.log("Name is provided.");
} else {
    console.log("Name is missing.");
}

In this scenario, an empty string is considered falsy, so the output will be Name is missing.

When to Use Ternary Operator Instead

JavaScript offers a shorthand version of if…else called the ternary operator. It’s useful for simple conditionals and improves code brevity.

let age = 16;
let message = age >= 18 ? "Adult" : "Minor";

console.log(message);

This single line replaces the following block:

if (age >= 18) {
    message = "Adult";
} else {
    message = "Minor";
}

However, avoid stacking ternary operators — it can make your code hard to read.

Enhancing Readability with Formatting

Neatly formatted if…else statements improve readability, especially in larger projects. Stick to proper indentation and use comments where necessary.

Here’s a before and after comparison:

Poorly formatted:

if(x>10){console.log("Too big");}else{console.log("OK");}

Well formatted:

if (x > 10) {
    console.log("Too big");
} else {
    console.log("OK");
}

While the functionality is the same, the second version is far easier to understand.

Real-World Use Cases

Let’s look at a couple of real-world scenarios using if…else statements:

1. Login Validation

let username = "user123";
let password = "abc123";

if (username === "user123" && password === "abc123") {
    console.log("Login successful!");
} else {
    console.log("Invalid credentials.");
}

2. Pricing Logic

let customerType = "regular";
let price = 100;

if (customerType === "premium") {
    price *= 0.9; // 10% discount
} else if (customerType === "student") {
    price *= 0.8; // 20% discount
}

console.log("Final price:", price);

Using conditional logic like this in your app helps tailor the experience for different users and scenarios.

Conclusion

Mastering the if…else statement is critical for any JavaScript developer. It may seem basic at first, but its versatility allows developers to implement logic that is core to nearly every application. From simple checks to complex workflows, if…else provides the control structure you need to bring decision-making into your code.

Take time to not only understand how it works, but to write clean, readable, and optimized conditionals that make your code more maintainable and effective in the long run.