Comparison Operators
Comparison operators compare two values and return a boolean (true or false).
Equality Operators:
| Operator | Description | Example | Result |
|---|---|---|---|
| == | Equal (with type coercion) | "5" == 5 | true |
| === | Strict equal (no coercion) | "5" === 5 | false |
| != | Not equal (with coercion) | "5" != 5 | false |
| !== | Strict not equal | "5" !== 5 | true |
Relational Operators:
| Operator | Description | Example | Result |
|---|---|---|---|
| > | Greater than | 5 > 3 | true |
| < | Less than | 5 < 3 | false |
| >= | Greater than or equal | 5 >= 5 | true |
| <= | Less than or equal | 5 <= 3 | false |
Best Practice: Always use === and !== to avoid unexpected type coercion bugs.
String Comparison: Strings are compared character by character using Unicode values:
- "apple" < "banana" (true - 'a' comes before 'b')
- "2" > "10" (true - comparing first characters '2' vs '1')
Code Examples
Comparison Operationsjavascript
// Equality operators
console.log(5 == "5"); // true (type coercion)
console.log(5 === "5"); // false (strict - different types)
console.log(5 !== "5"); // true (strict not equal)
// null and undefined
console.log(null == undefined); // true
console.log(null === undefined); // false
// Relational operators
console.log(10 > 5); // true
console.log(10 < 5); // false
console.log(10 >= 10); // true
console.log(10 <= 9); // false
// String comparison (alphabetical)
console.log("apple" < "banana"); // true
console.log("Apple" < "apple"); // true (uppercase comes first)
console.log("10" < "9"); // true (string comparison!)
console.log(10 < 9); // false (number comparison)
// Comparing different types
console.log("10" > 5); // true (string converted to number)
console.log("ten" > 5); // false (NaN is not > 5)Always be careful when comparing different types. Use === for predictable behavior.
Quick Quiz
1. What is the result of null === undefined?
2. Why should you use === instead of ==?
Was this lesson helpful?