Kar

Kar started this conversation 1 week ago.

Incorrect Equality Comparison: == vs === and Type Coercion Pitfalls ❓ Problem Statement

I'm comparing values in JavaScript and seeing unexpected results—like '0' == 0 returning true, or empty arrays comparing greater than expected. Why does this happen, and which should I use?

Digiaru

Posted 1 week ago

== performs type coercion, converting operands to a common type before comparison, which can lead to surprising behavior. In contrast, === does strict comparison (value + type) without coercion, making it more predictable RedditMedium+3itsmybot.com+3Reddit+3. Common gotchas: • "5" == 5 → true, but "5" === 5 → false. • [] == '' → true, due to coercion; but [] === '' → false. Best Practices: • Prefer === and !== for clarity and safety. • Explicitly convert types when needed (e.g. Number() or String()) MediumLinkedIn.


🧷 Suggested Tags for Posting • Floating-point issue: javascript, floating-point, precision, decimal.js, finance • Loop closure bug: javascript, closures, loops, var-vs-let, event-handling • Equality operator bug: javascript, type-coercion, == vs ===, best-practices