How to use comparison operators in JavaScript correctly

· Category: JavaScript

Short answer

Use strict equality (=== and !==) to compare both value and type, and relational operators (>, <, >=, <=) for numeric or lexicographic ordering.

Steps

  1. Prefer strict equality to avoid coercion surprises: javascript 0 === false; // false 0 == false; // true (coerced)
  2. Compare strings lexicographically by Unicode code points: javascript 'apple' < 'banana'; // true
  3. Compare objects by reference, not content: javascript {} === {}; // false
  4. Use Object.is() for edge cases like NaN and signed zero: javascript Object.is(NaN, NaN); // true Object.is(+0, -0); // false

Tips

  • Always use === unless you explicitly need coercion.
  • NaN is not equal to anything, including itself; use Number.isNaN().

Common issues

  • null >= 0 is true while null == 0 is false due to abstract relational comparison rules.
  • Comparing mixed types with == produces unpredictable results.