HeadlinesBriefing favicon HeadlinesBriefing.com

JavaScript Equality: Why == Is Lying to You

DEV Community •
×

The JavaScript equality operator (==) is often misunderstood, leading to subtle bugs. It uses a hidden 'Abstract Equality Comparison' algorithm that performs type coercion, which can yield counterintuitive results. For instance, an empty array [] coerces to 0, making [] == false evaluate to true.

Similarly, null is a unique case, equaling only undefined and no other value. A notorious issue involves NaN, which is not equal to itself, requiring Number.isNaN() for detection. Floating-point arithmetic also presents challenges, as 0.1 + 0.2 does not equal 0.3 due to IEEE-754 binary representation standards.

The strict equality operator (===) avoids these pitfalls by refusing type conversion, making code more predictable and easier to debug. Understanding these distinct behaviors is critical for writing robust code and is a frequent topic in technical interviews.