Home >Web Front-end >JS Tutorial >Why Does ` 0 === -0` Evaluate to True in JavaScript, While `Object.is(-0, 0)` Returns False?
The Difference and Equality of 0 and -0
The ECMAScript 5.1 specification distinguishes between 0 and -0, raising the question of why 0 === -0 evaluates to true.
IEEE 754 Standard
JavaScript employs the IEEE 754 standard for representing numbers. According to IEEE 754, signed zero allows for positive zero ( 0) and negative zero (-0). This distinction is required for floating-point arithmetic, as 1/-0 = -∞ and 1/ 0 = ∞.
Strict Equality Comparison Algorithm
Despite the technical distinction, section 11.9.6 of the specification explicitly defines the behavior of the strict equality comparison algorithm for 0 and -0:
Logical and Practical Rationale
Logically, it makes sense to treat 0 and -0 as equal. Distinguishing between them would complicate code, especially when working with zero.
Object.is Comparison Method
ES2015 introduced Object.is for more precise comparisons. Object.is explicitly distinguishes between 0 and -0:
Object.is(-0, +0); // false
The above is the detailed content of Why Does ` 0 === -0` Evaluate to True in JavaScript, While `Object.is(-0, 0)` Returns False?. For more information, please follow other related articles on the PHP Chinese website!