Codectionary / Developer documentation / JavaScript

Comparison Operators

Comparison operators compare two values and return a boolean. == and != perform type coercion before comparing (loose equality), while === and !== compare both value and type without coercion (strict equality). Relational operators (<, >, <=, >=) compare numeric or string ordering.

Syntax

a === b, a !== b, a > b, a <= b

Examples

Strict vs Loose Equality

The critical difference between == and ===.

console.log(5 == "5");   // true - "5" is coerced to a number
console.log(5 === "5");  // false - different types
console.log(0 == false); // true - false is coerced to 0
console.log(null == undefined);  // true
console.log(null === undefined); // false

Relational Comparisons

Comparing numbers and strings for ordering.

console.log(10 > 5);   // true
console.log(10 <= 10); // true
console.log("apple" < "banana"); // true - lexicographic (alphabetical) comparison
console.log("10" < "9"); // true - compared as strings, not numbers!

Best practices

  • Always prefer === and !== over == and != to avoid unpredictable type coercion bugs
  • Be aware that comparing strings uses lexicographic (dictionary) order, which can surprise you with numeric-looking strings
  • Use Object.is() for the rare edge cases where even === behaves unexpectedly (like NaN and -0)
  • Explicitly convert types with Number() or String() before comparing rather than relying on implicit coercion

At a glance

Purpose
Application logic and interaction
File extension
.js ยท .mjs
Runs in
Browsers and JavaScript runtimes
Usually used with
HTML, CSS and Web APIs

Specifications & further reading

Related JavaScript documentation