Comparison Operators

Comparing values is a foundational operation in any programming language. While basic inequalities are standard, JavaScript introduces some unique quirks when testing for equality.

Inequality Operators

The standard inequality operators work exactly as you would expect:

5 < 6;  // evaluates to true
5 > 6;  // evaluates to false
5 >= 6; // evaluates to false
5 <= 6; // evaluates to true

Strict vs. Loose Equality

This is where JavaScript gets strange. There are two different sets of equality operators: strict and loose.

Strict Equality (=== and !==)

To compare two values to see if they are exactly the same in both value and type, use the strict operators. This is highly recommended in almost all situations.

5 === 6; // evaluates to false
5 !== 6; // evaluates to true

Loose Equality (== and !=)

The “normal” loose equality operators are flexible. If the types do not match, JavaScript will attempt to automatically convert them before comparing.

5 == 6;   // evaluates to false
5 == "5"; // evaluates to true (Number and String match!)

5 != 6;   // evaluates to true
5 != "5"; // evaluates to false

Because loose equality (==) can lead to unpredictable bugs where a string conceptually matches a number, you should generally stick with strict equality (===) in nearly all cases.

Practical Example

When verifying if a condition is true, always prefer strict equality to ensure type safety.

// Good practice
console.log(5 > 6);       // false
console.log(5 === 6);     // false
console.log(5 === "5");   // false (Strictly prevents matching different types)
console.log(6 >= 6);      // true