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
- Prefer strict equality to avoid coercion surprises:
javascript 0 === false; // false 0 == false; // true (coerced) - Compare strings lexicographically by Unicode code points:
javascript 'apple' < 'banana'; // true - Compare objects by reference, not content:
javascript {} === {}; // false - Use
Object.is()for edge cases likeNaNand signed zero:javascript Object.is(NaN, NaN); // true Object.is(+0, -0); // false
Tips
- Always use
===unless you explicitly need coercion. NaNis not equal to anything, including itself; useNumber.isNaN().
Common issues
null >= 0is true whilenull == 0is false due to abstract relational comparison rules.- Comparing mixed types with
==produces unpredictable results.