Are 0 and -0 the Same in JavaScript?
Despite the distinction made in the ECMAScript 5.1 specification, 0 and -0 evaluate to true using strict equality in JavaScript.
Why is this?
JavaScript adopts the IEEE 754 standard for numerical representation. According to this standard, signed zero can exist in two forms: 0 (positive zero) and -0 (negative zero). However, division by 0 or -0 results in ∞ and -∞, respectively, rather than undefined.
Technically, this distinction between 0 and -0 is crucial. However, JavaScript provides an exception in its strict equality algorithm. Section 11.9.6 explicitly states that 0 and -0 are treated as equal in strict equality comparisons.
This exception aligns with the logical notion of treating 0 and -0 as equivalent. Additionally, it simplifies development by eliminating the need to consider this distinction in code.
Note:
ES2015 introduced Object.is as a new comparison method. Unlike the loose and strict equality operators, Object.is expressly distinguishes between 0 and -0:
Object.is(-0, +0); // false
The above is the detailed content of Are 0 and -0 Considered Equal in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!