== vs === and Coercion
Why loose equality is unpredictable, and the handful of cases where == is actually the right call.
a === b
x == null // null OR undefined
Object.is(a, b)Strict equality === compares value and type with no conversion. Loose equality == runs a coercion algorithm first, and that algorithm is where the famous WTF moments live.
console.log(0 == ''); // false
console.log(0 == '0'); // true
console.log('' == '0'); // false (not transitive!)
console.log([] == ![]); // true ([] becomes '', ![] becomes false -> 0)The rule that actually helps
Use === everywhere. There is exactly one useful loose comparison worth memorising: x == null is true for both null and undefined and nothing else. It is the cleanest nullish check that predates ??.
Object.is
For the two edge cases === gets philosophically wrong, use Object.is: it treats NaN as equal to itself and distinguishes +0 from -0.
Example
When to use it
- Use strict equality when comparing a form field value to the string '0' so the number 0 is not treated the same.
- Prefer === over == in all comparisons to eliminate type-coercion surprises discovered during code review.
- Use Object.is to correctly detect NaN in a numeric validation utility.
More examples
Strict vs loose equality pitfalls
Shows how loose == performs type coercion, causing counter-intuitive results that strict === avoids.
console.log(0 == false); // true β loose
console.log(0 === false); // false β strict
console.log("" == false); // true β loose
console.log("" === false); // false β strictObject.is for edge cases
Object.is handles the two cases where === gives surprising results: NaN identity and signed zeros.
console.log(NaN === NaN); // false β IEEE quirk
console.log(Object.is(NaN, NaN)); // true
console.log(Object.is(+0, -0)); // false
console.log(+0 === -0); // trueEquality with type coercion algorithm
Demonstrates that null only loosely equals undefined and nothing else, a common interview question.
console.log(null == undefined); // true β only these two
console.log(null === undefined); // false
console.log(null == 0); // false
console.log(null == false); // false
Discussion