Home > Article > Web Front-end > How Do 0 and -0 Differ in JavaScript, Despite Strict Equality Treating Them as Equal?
The Distinction between 0 and -0 in ECMAScript 5.1
The ECMAScript 5.1 specification explicitly distinguishes between 0 and -0, despite them evaluating to the same value when compared. This distinction stems from the implementation of floating-point numbers in JavaScript using the IEEE 754 standard.
The IEEE 754 standard requires both 0 and -0 for technical reasons related to numeric operations and division by zero. However, despite this technical distinction, the strict equality comparison in JavaScript treats 0 and -0 as equal.
According to the Strict Equality Comparison Algorithm defined in the ECMAScript 5.1 specification, if both operands are numbers, the comparison will return true even if one is 0 and the other is -0. This special case is explicitly defined in the algorithm:
- If x is +0 and y is −0, return true. - If x is −0 and y is +0, return true.
This allows for practical reasons, as differentiating between 0 and -0 would potentially require special handling in JavaScript code. To explicitly distinguish between them, the Object.is comparison method introduced in ES2015 can be used, as it returns false when comparing 0 to -0.
The above is the detailed content of How Do 0 and -0 Differ in JavaScript, Despite Strict Equality Treating Them as Equal?. For more information, please follow other related articles on the PHP Chinese website!