Randomblue Randomblue - 6 months ago 24
Javascript Question

Differentiating +0 and -0

It turns out

+0 === -0
evaluates to
true
despite
+0
and
-0
being different entities. So, how do you differentiate
+0
from
-0
?

There is a hack:

if (1 / myZero > 0) {
// myZero is +0
} else {
// myZero is -0
}


Can I do better?

Answer

In ECMAScript 6 Object.is behaves like === except that it distinguishes positive and negative zeroes, and Object.is(NaN, NaN) evaluates to true. (See here for a writeup.)

Chrome 24 supports Object.is.

Comments