A comparison operator compares two values and returns a boolean.
| Operator | Meaning |
|---|---|
> | greater than |
< | less than |
>= | greater than or equal |
<= | less than or equal |
=== | equal (strict) |
!== | not equal (strict) |
const age = 18;
console.log(age > 17); // → true
console.log(age >= 18); // → true
console.log(age < 18); // → false
console.log(age === 18); // → true
console.log(age !== 18); // → false
Comparing strings
Strings are compared character by character using their Unicode order. Capital letters come before lowercase ones.
console.log("apple" < "banana"); // → true
console.log("a" < "B"); // → false
console.log("Zebra" < "apple"); // → true
For sorting words for people, use localeCompare() instead, which follows language rules: "a".localeCompare("B").
Comparing different types
When the types differ, the loose operators try to convert them first. That is where surprises start.
console.log("10" > 9); // → true ("10" becomes the number 10)
console.log("10" > "9"); // → false (both strings: "1" comes before "9")
The same two values give different answers depending on their type. Convert to numbers first whenever you mean numeric comparison.
NaN is never equal to anything
console.log(NaN === NaN); // → false
console.log(Number.isNaN(NaN)); // → true
To check for NaN, use Number.isNaN(), see Numbers.
Equality has its own lesson, because the difference between == and === is one of the most asked beginner questions: Strict vs Loose Equality.