Strict Equality (===) Required
ID |
javascript.strict_equals |
Severity |
high |
Remediation Complexity |
trivial |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Reliability |
Language |
JavaScript |
Tags |
best-practice, reliability |
Description
Reports the loose-equality operators == and !=, which apply implicit type coercion before comparing. The coercion rules produce many surprising true/false outcomes; almost all of them are bugs. Use === and !==.
Two idiomatic shapes are exempt. The first is x == null (or null == x), a common shorthand for "x is null or undefined`". The second is `typeof x == "object" and its mirror image: typeof evaluates to a string whatever its operand, so comparing it against a string literal has nothing to coerce and == is indistinguishable from === there. The other operand must be a literal string — typeof x == y still coerces when y holds a number, so it is still reported. Every other use of == / != is flagged.
Rationale
-
"" == 0,"0" == false,[] == false,[] == ![]are alltrue. Each one has bitten thousands of developers. -
null == undefinedistruebutnull === undefinedisfalse— the asymmetry hides bugs. -
Type-aware comparisons document intent. Readers and tools (TypeScript, refactoring engines) can reason about typed equality far better than coerced equality.
// Bad - all coerce silently
if (count == "0") { ... }
if (status != 0) { ... }
Remediation
Use === / !==. Keep the x == null shorthand only when you specifically want "null or undefined".
// Good
if (count === 0) { ... }
if (status !== 0) { ... }
// Allowed - null-or-undefined check
if (value == null) { ... }
// Allowed - typeof yields a string, so there is nothing to coerce
if (typeof module == "object") { ... }