How to Use Comparison Operators in JavaScript: Syntax and Examples
In JavaScript, use
==, ===, !=, !==, <, <=, >, and >= to compare values. The === and !== operators check both value and type, while == and != compare values with type conversion.Syntax
Comparison operators compare two values and return true or false. Here are the main operators:
==: Equal to (compares values with type conversion)===: Strict equal to (compares value and type)!=: Not equal to (compares values with type conversion)!==: Strict not equal to (compares value and type)<: Less than<=: Less than or equal to>: Greater than>=: Greater than or equal to
javascript
value1 == value2 value1 === value2 value1 != value2 value1 !== value2 value1 < value2 value1 <= value2 value1 > value2 value1 >= value2
Example
This example shows how to use different comparison operators and their results.
javascript
const a = 5; const b = '5'; console.log(a == b); // true because values are equal after type conversion console.log(a === b); // false because types differ (number vs string) console.log(a != b); // false because values are equal after type conversion console.log(a !== b); // true because types differ console.log(a < 10); // true console.log(a >= 5); // true console.log(a > 10); // false
Output
true
false
false
true
true
true
false
Common Pitfalls
Using == and != can cause unexpected results because they convert types before comparing. Always prefer === and !== to avoid bugs.
Also, be careful when comparing null or undefined with == as it can be confusing.
javascript
const x = 0; const y = false; // Wrong: uses == which converts types console.log(x == y); // true (unexpected for some) // Right: uses === which checks type and value console.log(x === y); // false
Output
true
false
Quick Reference
| Operator | Meaning | Example | Result |
|---|---|---|---|
| == | Equal (with type conversion) | 5 == '5' | true |
| === | Strict equal (no type conversion) | 5 === '5' | false |
| != | Not equal (with type conversion) | 5 != '6' | true |
| !== | Strict not equal (no type conversion) | 5 !== '5' | true |
| < | Less than | 3 < 5 | true |
| <= | Less than or equal | 5 <= 5 | true |
| > | Greater than | 7 > 10 | false |
| >= | Greater than or equal | 7 >= 7 | true |
Key Takeaways
Use === and !== to compare both value and type safely.
Avoid == and != to prevent unexpected type coercion.
Comparison operators return true or false based on the comparison.
Use <, <=, >, >= to compare numeric or string values.
Be cautious when comparing null or undefined with ==.