36

Why does JavaScript have -0?

 4 years ago
source link: https://medium.com/javascript-in-plain-english/why-does-javascript-have-0-9b6e1965a075
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

JavaScript has two zeroes: -0 and +0. They are somehow both the same and different.

Dec 3 ·2min read

IBZRryB.png!web

Using strict equality comparison, -0 and +0 are equal

A Tale of Two Zeroes

Since the early versions of JavaScript there have always been two ways of performing equality comparison :

==
===

ES6 delivered a third option in the form of the Object.is method. It has some slight differences that hint at problems you did not even know you had. For instance, how would you tell JavaScript’s two zeroes apart?

Perhaps a better question is, JavaScript has two zeroes? Why does JavaScript have two zeroes? Why would any language have two zeroes?

The name for this is Signed Zero and turns out to be quite common among languages that implement the IEEE 754 floating-point standard. For example, two zeroes are also present in Ruby .

The two zeroes in question are:

+0
-0

As one might expect, they are treated as “the same” by both equality comparisons methods above. After all, zero is zero.

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

That is where Object.is comes in. It treats the two zeroes as unequal.

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

Pre-ES6 it is still possible to tell the two zeroes apart. Looking at the results from other operators offers a hint.

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

The last two operations in particular are useful. Unlike say Ruby or Python where division by zero yields a ZeroDivisionError , JavaScript returns Infinity . Now take a look at the polyfill for Object.is offered on MDN.

Since division by signed zero in JavaScript returns signed infinity, those results can be compared to tell the two zeroes apart.

Resources

TLDR

Object.is

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK