Learn JavaScript Comparison and Logical Operators with Examples for Beginners

JavaScript operators are essential building blocks that help us make decisions in our code. In this comprehensive guide, we’ll explore comparison and logical operators, understand how they work, and practice with real-world examples. Whether you’re building interactive web applications or writing simple scripts, these operators form the foundation of programming logic.

Understanding Comparison Operators

Comparison operators allow us to compare values and return boolean results (true or false). These operators are fundamental to creating conditional statements and making decisions in your code.

The Equality Operator (==)

The equality operator compares two values for equality, performing type coercion if necessary. This means it attempts to convert values to the same type before comparison.

let number = 5;
let stringNumber = "5";

console.log(number == stringNumber);  // Output: true
console.log(100 == "100");           // Output: true

IIn the first example, 5 == '5' returns true because JavaScript converts the string '5' to a number before comparing. This is called type coercion. However, this can lead to unexpected results, so use === for strict equality.

The Strict Equality Operator (===)

The strict equality operator compares both value and type, ensuring more predictable comparisons. No type conversion occurs during the comparison.

let number = 5;
let stringNumber = "5";

console.log(number === stringNumber);  // Output: false
console.log(100 === "100");           // Output: false
console.log(100 === 100);             // Output: true

This operator ensures that both the value and type match exactly. Notice how comparing a number and string now returns false, even when their values are equivalent.

Inequality Operators (!= and !==)

These operators check if values are not equal to each other. Like their equality counterparts, they come in loose (!==) and strict (!==) versions.

let age = 25;
let ageLimit = "25";

console.log(age != ageLimit);    // Output: false
console.log(age !== ageLimit);   // Output: true

let status = "active";
console.log(status != "inactive");  // Output: true

The loose inequality operator performs type coercion, while the strict version considers both value and type. Understanding these differences helps prevent bugs in your code.

Greater Than (>) and Less Than (<) Operators

These operators compare numerical values or strings (alphabetically) to determine their relationship.

let score = 85;
let passingGrade = 70;

console.log(score > passingGrade);      // Output: true
console.log(score < 60);                // Output: false

// String comparison
console.log("apple" < "banana");        // Output: true
console.log("zebra" > "yellow");        // Output: true

When comparing strings, JavaScript uses alphabetical ordering. Each character is compared based on its Unicode value until a difference is found.

Greater Than or Equal To (>=) and Less Than or Equal To (<=)

These operators combine comparison and equality checks into a single operation.

let temperature = 98.6;
let normalTemp = 98.6;

console.log(temperature >= normalTemp);   // Output: true
console.log(temperature <= 99);           // Output: true
console.log(95 <= temperature);           // Output: true

These operators are particularly useful when checking ranges or boundary conditions in your code.

Understanding Logical Operators

Logical operators allow us to combine multiple conditions and make complex decisions. They are essential for creating sophisticated program logic.

The AND Operator (&&)

The AND operator returns true only if all conditions are true. It’s perfect for checking multiple requirements simultaneously.

let age = 25;
let hasLicense = true;
let goodVision = true;

let canDrive = age >= 18 && hasLicense && goodVision;
console.log(canDrive);  // Output: true

let isEligible = age >= 21 && hasLicense && !goodVision;
console.log(isEligible);  // Output: false

The AND operator ensures all conditions must be met. If any condition is false, the entire expression becomes false.

The OR Operator (||)

The OR operator returns true if at least one condition is true. It’s useful for providing alternative paths in your code.

let isStudent = false;
let isSenior = true;
let hasDiscount = false;

let getsDiscount = isStudent || isSenior || hasDiscount;
console.log(getsDiscount);  // Output: true

let noAccess = false || false || false;
console.log(noAccess);  // Output: false

The OR operator is perfect for situations where meeting any one of several conditions is sufficient.

The NOT Operator (!)

The NOT operator inverts a boolean value, turning true to false and vice versa. It’s helpful for checking if something is not true.

let isLoggedIn = true;
console.log(!isLoggedIn);  // Output: false

let isEmpty = "";
console.log(!isEmpty);     // Output: true
console.log(!!isEmpty);    // Output: false

The double NOT operator (!!) is a quick way to convert a value to its boolean equivalent.

Combining Operators for Complex Conditions

In real-world applications, we often need to combine multiple operators to create complex conditions.

let age = 20;
let hasParentalConsent = true;
let hasPaidFee = true;

let canRegister = (age >= 18 || (age >= 16 && hasParentalConsent)) && hasPaidFee;
console.log(canRegister);  // Output: true

This example demonstrates how parentheses can be used to group conditions and control the order of evaluation.

Common Pitfalls and Best Practices

Type Coercion Gotchas

console.log(0 == false);      // Output: true
console.log("" == false);     // Output: true
console.log(null == undefined);  // Output: true
console.log([] == false);     // Output: true

// Using strict equality prevents unexpected behavior
console.log(0 === false);     // Output: false
console.log("" === false);    // Output: false

These examples highlight why using strict equality (===) is generally recommended to avoid unexpected type coercion.

Short-Circuit Evaluation

JavaScript’s logical operators use short-circuit evaluation, which can be leveraged for concise code.

let userInput = "";
let defaultValue = "Guest";

// If userInput is falsy, use defaultValue
let displayName = userInput || defaultValue;
console.log(displayName);  // Output: "Guest"

// Short-circuit with AND
let isAdmin = true;
isAdmin && console.log("Welcome, Admin!");  // Output: "Welcome, Admin!"

Short-circuit evaluation can make your code more efficient and elegant when used appropriately.

Practical Examples

Example 1: Check if a Number is Positive and Even

let number = 8;

if (number > 0 && number % 2 === 0) {
  console.log('The number is positive and even.');
} else {
  console.log('The number is not positive or not even.');
}

This code checks if the number is greater than 0 and divisible by 2. If both conditions are true, it logs a message indicating the number is positive and even.

Example 2: Determine the Largest of Three Numbers

function checkAccess(user) {
    return user.isAdmin || 
           (user.role === "editor" && user.isActive) || 
           (user.role === "viewer" && user.hasSubscription);
}

let user = {
    role: "editor",
    isActive: true,
    isAdmin: false,
    hasSubscription: false
};

console.log(checkAccess(user));  // Output: true

This code compares three numbers using ‘&&' to determine which one is the largest. It uses else if for multiple conditions.

Example 3: Check if a User is Eligible for a Discount

let isMember = true;
let purchaseAmount = 120;

if (isMember || purchaseAmount > 100) {
  console.log('You are eligible for a discount.');
} else {
  console.log('You are not eligible for a discount.');
}

This code uses the '||‘ operator to check if the user is a member or if their purchase amount exceeds 100. If either condition is true, they get a discount.

Conclusion

Understanding comparison and logical operators is crucial for writing effective JavaScript code. These operators form the foundation of program logic and decision-making in your applications. Remember to:

  • Use strict equality (===) when type checking is important
  • Leverage short-circuit evaluation for cleaner code
  • Combine operators thoughtfully for complex conditions
  • Test your conditions thoroughly to ensure expected behavior

Previous Article

Understanding JavaScript Type Conversions with Real Examples

Next Article

How to Write JavaScript if else Statements with Examples

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 ✨