Skip to content

JavaScript Comparison Operators

Comparison operators in JavaScript are essential for making decisions in your code by comparing values. This guide provides a deep dive into JavaScript comparison operators, enriched with practical examples, clear explanations, and a special focus on some unusual behaviors that can occur with certain data type comparisons.

Introduction to Comparison Operators

Comparison operators compare two values and return a Boolean value (true or false) based on whether the comparison is true. There are several key comparison operators in JavaScript:

  • == (Loose equality)
  • === (Strict equality)
  • != (Loose inequality)
  • !== (Strict inequality)
  • > (Greater than)
  • < (Less than)
  • >= (Greater than or equal to)
  • <= (Less than or equal to)

Each operator has a specific role, and understanding the differences between them is crucial for accurate programming.

Loose vs. Strict Comparison

Loose Equality (==)


Output appears here after Run.

Explanation: Here, 1 and "1" seem different (one is a number and the other is a string), but == changes both to the same type before comparing them. This is why they are considered equal.

Strict Equality (===)


Output appears here after Run.

Explanation: This time, 1 and "1" are not considered equal because === checks if the value and the type are exactly the same. Here, they are not the same type.

Inequality Operators

Loose Inequality (!=)


Output appears here after Run.

Explanation: 1 and "2" are different. != also changes types to compare, but since the values are different after type conversion, it returns true.

Strict Inequality (!==)


Output appears here after Run.

Explanation: Here, !== finds the values different because it checks without changing the type. Since the types (number vs. string) are different, it returns true.

Relational Operators


Output appears here after Run.

Explanation: These examples show basic comparisons:

  • x < y is true because 5 is less than 10.
  • x > y is false because 5 is not greater than 10.
  • x <= 5 is true because 5 is equal to 5.
  • y >= 11 is false because 10 is not greater than or equal to 11.

Note on string comparison: When < and > are used with strings, JavaScript compares them lexicographically (by Unicode value). For example, 'b' > 'a' is true, but '10' < '2' is also true because the comparison happens character by character.

Practical Applications of Comparison Operators

Sorting Functions


Output appears here after Run.

Explanation: This code sorts numbers in ascending order. The sort function compares each pair of numbers, arranging them from smallest to largest.

Conditional Logic


Output appears here after Run.

Explanation: This code checks if age is 18 or more. If yes, it prints "You are an adult." If not, it prints "You are not an adult."

JavaScript's Weird Behaviors

JavaScript sometimes shows weird behavior when comparing unusual data types:


Output appears here after Run.

Explanation:

  • [] == 0: An empty array is considered equal to zero because when the array is converted to a number, it becomes 0.
  • [] == ![]: This seems very weird, but here's what happens: ![] converts the array to a boolean (which is true because arrays are truthy), then negates it to false. When comparing [] to false, both are converted to numbers (0 and 0), hence they are "equal."

Let's delve into more examples of JavaScript's unusual behavior in comparisons and other operations.

Comparing Arrays and Objects

JavaScript's loose equality checks can yield unexpected results when comparing arrays and objects due to how these data structures are converted and compared.


Output appears here after Run.

Explanation:

  • [] == [] and {} == {}: Even though both sides of the comparison seem identical, they are different instances in memory. JavaScript checks object and array equality based on their memory address, not their contents.
  • [] == ![]: This case follows the same coercion rules explained in the previous section.

Null vs. Undefined

The comparison between null and undefined with loose equality also shows unusual behavior, but they do share some similarities in JavaScript.


Output appears here after Run.

Explanation:

  • null == undefined: JavaScript treats null and undefined as loosely equal, which is an exception in the loose equality rules.
  • null === undefined: Since they are different types, strict equality returns false.
  • null == 0, null > 0, and null >= 0: In relational comparisons, null coerces to 0, so null >= 0 becomes 0 >= 0, which evaluates to true. However, null == 0 and null > 0 remain false because null only coerces to 0 in relational contexts, not in loose equality.

Boolean and Non-Boolean Comparisons

Comparing booleans to non-booleans using loose equality can lead to counterintuitive results due to type coercion into numbers.


Output appears here after Run.

Explanation:

  • true == 1 and false == 0: In JavaScript, true converts to 1 and false to 0, hence these comparisons return true.
  • true == 2: Since true converts to 1, it does not equal 2.
  • true == "1" and false == "0": The strings are converted to numbers, matching the numbers that true and false convert to.

Using Object.is for Comparisons

For those needing precise comparisons, especially with edge cases like NaN and +0 vs. -0, JavaScript provides Object.is.


Output appears here after Run.

Explanation:

  • Object.is(NaN, NaN): Unlike the equality operators, Object.is correctly identifies two NaN values as the same.
  • Object.is(+0, -0): Object.is distinguishes between positive and negative zero, which equality operators do not.
  • Object.is(false, false): Demonstrates exact equality without coercion, returning true for identical primitive values.

Understanding these weird behaviors in JavaScript not only helps in avoiding potential pitfalls but also enhances the ability to debug complex issues effectively.

These examples illustrate why it's often safer to use strict comparison operators (=== and !==) that do not convert types automatically. This helps avoid unexpected results in your JavaScript code.

WARNING

Use strict comparison operators (=== and !==) in JavaScript to ensure type and value accuracy. This prevents unintended type coercion, making your comparisons more predictable and reliable. For instance, 0 === '0' yields false, highlighting the importance of matching types.

Best Practices

  • Prefer Strict Operators: Use === and !== to avoid errors from automatic type conversion.
  • Clear Conditions: Make your conditions clear and straightforward, especially when they involve comparisons.
  • Test Edge Cases: Always check edge cases in your comparisons, especially when handling user inputs or variable data types.

Conclusion

Understanding comparison operators in JavaScript is crucial for making correct decisions in your programs. By following these guidelines and understanding both typical and atypical behaviors, you can write more reliable and predictable code. As you continue to explore JavaScript, use these operators judiciously to manage various programming challenges effectively.

Practice

Which of the following comparison operators can be used in JavaScript?

Dual-run preview — compare with live Symfony routes.