JavaScript ==
vs ===
: Key Differences Explained
Understanding the difference between ==
(loose equality) and ===
(strict equality) is crucial for writing bug-free JavaScript code. Let’s break it down with examples.
1. ==
(Loose Equality)
Performs type coercion before comparing values. This means JavaScript converts types to match, which can lead to unexpected results.
Examples:
5 == '5'; // true (string '5' coerced to number)
true == 1; // true (boolean true coerced to 1)
null == undefined; // true (special case)
'0' == false; // true (both coerced to 0)
When to Use: Rarely. It can introduce subtle bugs due to implicit type conversion.
2. ===
(Strict Equality)
Checks both value and type without coercion. Safer and more predictable.
Examples:
5 === '5'; // false (number vs string)
true === 1; // false (boolean vs number)
null === undefined; // false (different types)
'0' === false; // false (string vs boolean)
When to Use: Always prefer ===
unless you explicitly need type coercion.
Key Takeaways
==
checks values after type coercion (risky).
===
checks values AND types (recommended).
- Avoid bugs by defaulting to
===
.
Interview Question:
Q: Why does [] == ![]
return true
in JavaScript?
A: Due to type coercion! ![]
becomes false
, and []
coerces to ""
then 0
, while false
coerces to 0
. Hence, 0 == 0
is true
.