Both == and === are comparison operators in JavaScript, but they differ in type checking.
1️⃣ == (Loose Equality)
- Compares values after performing type conversion (type coercion).
- If types differ, JavaScript tries to convert them before comparing.
Example:
console.log(5 == "5"); // true (string converted to number)
console.log(false == 0); // true (false converted to 0)
console.log(null == undefined); // true
✅ Use case: When you want to allow implicit conversions (rarely recommended).
2️⃣ === (Strict Equality)
- Compares both value and type.
- No type conversion is performed.
Example:
console.log(5 === "5"); // false (number vs string)
console.log(5 === 5); // true
console.log(false === 0); // false
✅ Use case: When you want to ensure both type and value match (best practice).
🔍 Summary Table
| Operator | Checks Type? | Performs Type Conversion? | Example | Result |
|---|---|---|---|---|
== |
❌ No | ✅ Yes | 5 == "5" |
true |
=== |
✅ Yes | ❌ No | 5 === "5" |
false |
💡 In Short:
Use
==for loose comparison (with coercion) and===for strict comparison (no coercion).
🔒 Always prefer===to avoid unexpected results.