gotchaModeratepending
JavaScript == vs === -- type coercion traps
Viewed 0 times
loose equalitystrict equalitytype coercioneqeqeqnull check
browsernodejs
Error Messages
Problem
Using == instead of === causes subtle bugs due to type coercion. 0 == '' is true, null == undefined is true, but null == 0 is false. The coercion rules are inconsistent and unpredictable.
Solution
Always use === (strict equality) and !== (strict inequality). The only acceptable use of == is checking for null/undefined together: if (x == null) catches both null and undefined. Use ESLint rule eqeqeq to enforce this.
Why
== performs type coercion before comparison using the Abstract Equality Algorithm, which has 12 different rules. === compares without coercion -- same type and same value.
Code Snippets
== vs === comparison traps
// Surprising == results
0 == '' // true
0 == '0' // true
'' == '0' // false (inconsistent!)
false == '0' // true
false == '' // true
null == undefined // true
null == 0 // false
NaN == NaN // false
// Always use ===
0 === '' // false (correct)
0 === '0' // false (correct)
// Only good use of ==
if (x == null) { /* catches null AND undefined */ }Revisions (0)
No revisions yet.