In a recent post on /. An author writes following without explanation which happens to be true.
0 === -0 //returns true
My understanding about === operator is it returns true if operands point to same object.
Also, - operator returns a reference to negative value of operand. With this rule, 0 and -0 should not be the same.
So, why is 0 === -0 ?
In a recent post on http://wtfjs./. An author writes following without explanation which happens to be true.
0 === -0 //returns true
My understanding about === operator is it returns true if operands point to same object.
Also, - operator returns a reference to negative value of operand. With this rule, 0 and -0 should not be the same.
So, why is 0 === -0 ?
Share Improve this question edited Aug 17, 2012 at 1:02 user166390 asked Aug 17, 2012 at 0:36 hrishikeshp19hrishikeshp19 9,03627 gold badges82 silver badges144 bronze badges3 Answers
Reset to default 7===
does not always mean point to the same object. It does on objects, but on value types, it pares the value. Hence how this works:
var x = 0;
var y = 0;
var isTrue = (x === y);
document.write(isTrue); // true
JavaScript used IEEE floating point standard where 0 and -0 are two different numbers, however, the ECMAScript standard states the parser must interpret 0 and -0 as the same:
§5.2 (page 12)
Mathematical operations such as addition, subtraction, negation, multiplication, division, and the mathematical functions defined later in this clause should always be understood as puting exact mathematical results on mathematical real numbers, which do not include infinities and do not include a negative zero that is distinguished from positive zero. Algorithms in this standard that model floating-point arithmetic include explicit steps, where necessary, to handle infinities and signed zero and to perform rounding. If a mathematical operation or function is applied to a floating-point number, it should be understood as being applied to the exact mathematical value represented by that floating-point number; such a floating-point number must be finite, and if it is +0 or -0 then the corresponding mathematical value is simply 0.
In fact, 0 and -0 are not the same even at the bit level. However, there is a special case implemented for +/-0 so they pare as equal.
The === operator pares by value when applied to primitive numbers.
Primitive numbers are not objects. You're doing a value parison of the numbers, not an identity parison of objects.
positive zero is equal to negative zero.
This is from the parison algorithm for the ===
operator
If Type(x) is Number, then
If x is NaN, return false.
If y is NaN, return false.
If x is the same Number value as y, return true.
If x is +0 and y is −0, return true.
If x is −0 and y is +0, return true.
Return false.