Start learning free

LESSON 74 OF 410 · CONDITIONAL STATEMENTS

Comparison Operators in JavaScript in JavaScript

Lesson Read the full explanation

When writing if statements, we usually compare two values using one or more comparison operators:

Operator Name Examples
== Equal  x == 5,  x == y
!= Not equal  x != 3,  x != y
> Greater than  x > 5,  x > y
< Less than  x < 8,  x < y
>= Greater than or equal to  x >= 4,  x >= y
<= Less than or equal to  x <= 3,   x <= y

For example:

10 == 10 // Evaluates to true
3 < 2 // Evaluates to false
15 >= 15 // Evaluates to true
17 != 12 // Evaluates to true

We usually use these operators with variables:

let a = 10;
let b = 15;

if (a == b) {
    console.log("a is equal to b");
}
if (a < b) {
    console.log("a is less than b");
}

The first condition is not satisfied since 10 == 15 evaluates to false.

The second condition is satisfied since 10 < 15 evaluates to true.

The code above prints "a is less than b".


Assignment
Follow the Coding Tutorial and let's play with comparison operators.


Hint
Look at the examples above if you get stuck.


STEP 1 OF 3
    Ctrl + Enter to check

    JAVASCRIPT · CONDITIONAL STATEMENTS

    Comparison Operators in JavaScript, explained

    Introduction

    In this lesson, we will explore comparison operators in JavaScript. Comparison operators are fundamental in programming as they allow us to compare values and make decisions based on those comparisons. They are commonly used in conditional statements, loops, and many other scenarios where decision-making is required.

    Understanding the Basics

    Comparison operators compare two values and return a boolean value (true or false). Here are the basic comparison operators in JavaScript:

    • ==: Equal to
    • !=: Not equal to
    • >: Greater than
    • <: Less than
    • >=: Greater than or equal to
    • <=: Less than or equal to

    Understanding these basics is crucial before moving on to more complex aspects of comparison operations.

    Main Concepts

    Let's delve deeper into each comparison operator with examples:

    // Equal to
    console.log(10 == 10); // true
    console.log(10 == '10'); // true (type coercion)
    
    // Not equal to
    console.log(10 != 5); // true
    console.log(10 != '10'); // false (type coercion)
    
    // Greater than
    console.log(10 > 5); // true
    console.log(10 > 15); // false
    
    // Less than
    console.log(10 < 15); // true
    console.log(10 < 5); // false
    
    // Greater than or equal to
    console.log(10 >= 10); // true
    console.log(10 >= 5); // true
    
    // Less than or equal to
    console.log(10 <= 10); // true
    console.log(10 <= 5); // false
    

    These examples illustrate how each operator works and the results they produce.

    Examples and Use Cases

    Comparison operators are widely used in various contexts. Here are some examples:

    let age = 18;
    
    // Check if age is equal to 18
    if (age == 18) {
        console.log("You are 18 years old.");
    }
    
    // Check if age is not equal to 18
    if (age != 18) {
        console.log("You are not 18 years old.");
    }
    
    // Check if age is greater than 18
    if (age > 18) {
        console.log("You are older than 18.");
    }
    
    // Check if age is less than 18
    if (age < 18) {
        console.log("You are younger than 18.");
    }
    
    // Check if age is greater than or equal to 18
    if (age >= 18) {
        console.log("You are 18 or older.");
    }
    
    // Check if age is less than or equal to 18
    if (age <= 18) {
        console.log("You are 18 or younger.");
    }
    

    These examples demonstrate how comparison operators can be used to make decisions based on variable values.

    Common Pitfalls and Best Practices

    Here are some common mistakes to avoid and best practices to follow:

    • Avoid using == and != for comparisons involving different data types. Use === and !== instead to avoid type coercion issues.
    • Always ensure that the values being compared are of the same type to avoid unexpected results.
    • Write clear and readable code by using meaningful variable names and comments.

    Advanced Techniques

    Advanced comparison techniques involve using logical operators in conjunction with comparison operators:

    let x = 10;
    let y = 20;
    let z = 30;
    
    // Using logical AND (&&)
    if (x < y && y < z) {
        console.log("x is less than y and y is less than z");
    }
    
    // Using logical OR (||)
    if (x > y || y < z) {
        console.log("Either x is greater than y or y is less than z");
    }
    

    These techniques allow for more complex decision-making in your code.

    Code Implementation

    Here is a well-commented code snippet demonstrating the correct use of comparison operators:

    let score = 85;
    
    // Check if score is greater than or equal to 90
    if (score >= 90) {
        console.log("Grade: A");
    }
    // Check if score is between 80 and 89
    else if (score >= 80 && score < 90) {
        console.log("Grade: B");
    }
    // Check if score is between 70 and 79
    else if (score >= 70 && score < 80) {
        console.log("Grade: C");
    }
    // Check if score is between 60 and 69
    else if (score >= 60 && score < 70) {
        console.log("Grade: D");
    }
    // If score is less than 60
    else {
        console.log("Grade: F");
    }
    

    This code snippet shows how to use comparison operators to determine a grade based on a score.

    Debugging and Testing

    When debugging code involving comparison operators, consider the following tips:

    • Use console.log() to print variable values and comparison results.
    • Write unit tests to verify the correctness of your comparison logic.

    Example test cases:

    function testComparisonOperators() {
        console.assert(10 == 10, "Test 1 Failed");
        console.assert(10 != 5, "Test 2 Failed");
        console.assert(10 > 5, "Test 3 Failed");
        console.assert(10 < 15, "Test 4 Failed");
        console.assert(10 >= 10, "Test 5 Failed");
        console.assert(10 <= 10, "Test 6 Failed");
    }
    
    testComparisonOperators();
    

    These test cases help ensure that your comparison logic works as expected.

    Thinking and Problem-Solving Tips

    When approaching problems involving comparison operators, consider the following strategies:

    • Break down complex conditions into simpler parts.
    • Use logical operators to combine multiple conditions.
    • Practice writing conditional statements to improve your problem-solving skills.

    Conclusion

    In this lesson, we covered the basics of comparison operators in JavaScript, their applications, and best practices. Mastering these concepts is essential for writing effective and efficient code. Keep practicing and exploring further applications to enhance your skills.

    Additional Resources

    For further reading and practice, consider the following resources:

    Keep going with JavaScriptAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free