7

In Javascript when you multiply

1 * 0 = 0

whereas

-1 * 0 = -0

Well, I can understand its technically 0, is there something different between 0 and -0 under the hood?

Faiz Mohamed Haneef
  • 3,418
  • 4
  • 31
  • 41
  • 2
    Yes, its how floating point numbers are represented, and is the reason `float === float` is often best avoided. – Keith Jul 25 '20 at 19:44
  • 2
    mathematically they are equal, but in binary they are represented differently. specifically the first bit is a 1 instead of 0 for -0. – Rick Jul 25 '20 at 20:04

3 Answers3

6

Interesting! It seems their values are equal--neither is larger than the other, but they are distinct objects with several side effects (including division by 0 or -0 as per Roisin's answer).

Other interesting quirks observed:

const a = 0;
const b = -0;

a == b; // true
a === b; // true

a < b; // false
b < a; // false

Object.is(a, b); // false
Object.is(a, -b); // true

b.toString(); // "0" <-- loses the negative sign

a + b; // 0
b - a; // -0
a * b; // -0

Arash Motamedi
  • 9,284
  • 5
  • 34
  • 43
  • 1
    This is true, depending on the equality comparison you use. For example. Object.is(+0, -0) === false – Róisín Grannell Jul 25 '20 at 19:52
  • 2
    The == and === in JS treat signed and unsigned 0 the same. This is standard in many (most?) languages that follow the IEEE-754 model, often requiring a different method to detect. – user2864740 Jul 25 '20 at 19:59
  • Having it like this is also uniform with x <= 0, x >= 0, x <= -0, and x >= -0. (Arguments about proper methods to compare aside.) – user2864740 Jul 25 '20 at 20:04
5

Yes, there is a difference. JavaScript has signed zeros, so the two are represented differently internally.

There are some practical differences too:

console.log(1 / +0 ===  Infinity) // true
console.log(1 / -0 === -Infinity) // true
Róisín Grannell
  • 2,048
  • 1
  • 19
  • 31
0

When you compare 0 === -0 you will get true but if you check with Object.is(0, -0) you will get false.

Object.is()

zb22
  • 3,126
  • 3
  • 19
  • 34