Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does javascript have a concept of negative zero

Consider the following

var l = console.log.bind(console);
l(-0); // 0
l(0); // 0
l(0 === -0); // true
l(0 == -0); // true
l(1 / 0); // Infinity
l(1 / -0); // -Infinity
  • Why is negative zero equal to zero ?
  • Given it's equal why does it behave differently ?

Bonus question:

  • Is the 0/-0 combination the only combination where equal objects behave differently?

I know NaN/NaN is a combination where non-equal objects behave the same.

like image 976
Raynos Avatar asked Jul 24 '11 15:07

Raynos


People also ask

Can JavaScript number be negative?

To use negative numbers, just place a minus (-) character before the number we want to turn into a negative value: let temperature = -42; What we've seen in this section makes up the bulk of how we will actually use numbers.

Is there such a thing as negative zero?

There's no such thing as negative zero. For a binary integer, setting the sign bit to 1 and all other bits to zero, you get the smallest negative value for that integer size. (Assuming signed numbers.) Negative zero is actually used in mathematical analysis, especially in limit calculations.

Does negative zero exist in Java?

The mystery of negative zero (-0) in Java. Mathematically the number 0 does not have a sign, therefore -0, +0 and 0 are identical. We say that zero is neither positive nor negative.


1 Answers

Why is negative zero equal to zero ?

Because IEEE 754 demands it.

Is the 0/-0 combination the only combination where equal objects behave differently?

I believe so. In Javascript, only Numbers have a special === algorithm, and 0, -0, NaN are the only special cases there (ECMA-262 §11.9.6).

like image 159
kennytm Avatar answered Sep 20 '22 16:09

kennytm