Comparison Operators in JavaScript
🧠 What Are Comparison Operators?
Comparison operators are used to compare two values. The result of a comparison is always a boolean: either true or false. These are the building blocks of conditionals in JavaScript.
>>“Comparisons help your code make decisions.” 🧭
📌 List of Comparison Operators
| Operator | Name | Example | Result |
|---|---|---|---|
| == | Equality | 5 == "5" | true |
| === | Strict Equality | 5 === "5" | false |
| != | Inequality | 4 != "5" | true |
| !== | Strict Inequality | 4 !== "4" | true |
| > | Greater Than | 10 > 5 | true |
| < | Less Than | 3 < 7 | true |
| >= | Greater Than or Equal To | 6 >= 6 | true |
| <= | Less Than or Equal To | 2 <= 3 | true |
💡 Type Coercion Warning
Note
Loose equality (==) performs type coercion.
5 == "5" → true
Strict equality (===) compares both value and type.
5 === "5" → false
5 == "5" → true
Strict equality (===) compares both value and type.
5 === "5" → false
📊 Examples
Basic Comparisons
console.log(5 == "5"); // true
console.log(5 === "5"); // false
console.log(10 != "10"); // false
console.log(10 !== "10"); // true
console.log(7 > 3); // true
console.log(2 < 1); // false
console.log(4 >= 4); // true
console.log(6 <= 5); // false🧪 Comparing Different Types
JavaScript tries to convert values to the same type when using ==. This can lead to unexpected results:
Weird Coercions
console.log(false == 0); // true
console.log("" == 0); // true
console.log(null == undefined); // true
console.log(null === undefined); // falseNote
Always prefer strict operators (=== and !==) to avoid bugs due to type coercion.
🔍 Real-World Use Case
If Statement with Comparison
const score = 85;
if (score >= 90) {
console.log("Excellent!");
} else if (score >= 75) {
console.log("Good job!"); // This line will run
} else {
console.log("Keep trying.");
}📚 Further Reading
>>“Comparisons are at the heart of every decision your app makes.” 🧠