Why is the value "0 === -0" true in JavaScript?

In a recent post http://wtfjs.com/ . The author writes the following without explanation, which, as it turns out, is true.

0 === -0 //returns true 

My understanding of the === operator returns true if the operands point to the same object.

In addition, - the operator returns a reference to the negative value of the operand. With this rule, 0 and -0 should not be the same.

So why is 0 === -0?

+7
source share
3 answers

In fact, 0 and -0 are not the same even at the bit level. However, for +/- 0 there is a special case, therefore they are compared as equal.

The === operator is compared by value when applied to primitive numbers.

+5
source

=== does not always mean a point for the same object. It works with objects, but by type of value, it compares the value. From here how it works:

 var x = 0; var y = 0; var isTrue = (x === y); document.write(isTrue); // true 

JavaScript uses the IEEE floating point standard, where 0 and -0 are two different numbers, however the ECMAScript standard states that the parser should interpret 0 and -0 as the same:

ยง5.2 (p. 12)

Mathematical operations such as addition, subtraction, negation, multiplication, division, and mathematical functions defined later in this section should always be understood as calculating exact mathematical results from mathematical real numbers that do not include infinity and do not include negative zero, which differs from positive zero . Algorithms in this standard that model floating point arithmetic include explicit steps, where necessary, for handling infinities with both zero sign and rounding. If a mathematical operation or function is applied to a floating-point number, it should be understood as applying to the exact mathematical value represented by this floating-point number; such a floating point number must be finite, and if it is +0 or -0, then the corresponding mathematical value will be just 0 .

+6
source

Primitive numbers are not objects. You are comparing the values โ€‹โ€‹of numbers, not matching the identity of objects.

positive zero is negative zero.

This is from the comparison 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 numeric 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.

  • Returns false.

+3
source

All Articles