Why JavaScript has +0 and -0 ?

This question had in my mind around many years and finally decide to give a try and understand why JavaScript has positive zero and negative zero.

In most of cases we use == or === to check value and type are the same for two operand.

-0 == +0 // true
-0 === +0 // true

In this case equal operators do not support.

So moving to next option, In JavaScript Object.is can be used to compare values. It’s more similar to === operand.

Object.is(0, -0) // false

Object.is(0, 0) //true
Object.is(0, '0') //false

This is proved that, Javascript has two zeros which are +0 and -0.

What is the purpose of having two zeros?

Let’s try to narrow down little bit.

-0 > +0 // false
+0 > -0 // false
-0 + -0 // -0
-0 + +0 // +0
+0 + +0 // +0
+1 / -0 // -Infinity
+1 / +0 // +Infinity
Infinity > 0 // true
-Infinity < -0 // true

When look at above result all together, JavaScript has two zeros but looks like on same position in number line.

We know, IEEE Institute of Electrical and Electronics Engineers, Standard for Floating-Point Arithmetic (IEEE 754)  was established in 1985 to make consistency across all electronic devices and address many issues found in division floating point numbers. So these rule directly applied to C and C++ which make later more abstracted in general purpose language such as Java, JavaScript, python to handle these issues.

When JavaScript was invented,-0 and +0 was added to language specification to address number divided by zero and result +Infinity or -Infinity base on signed of the zero. But on the other hand, Java or python throws an exception when divided by zero.

Leave a Reply