Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a difference between 0 and -0 in Javascript [duplicate]

Tags:

javascript

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?

like image 577
Faiz Mohamed Haneef Avatar asked Jul 25 '20 19:07

Faiz Mohamed Haneef


2 Answers

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

like image 130
Arash Motamedi Avatar answered Oct 19 '22 16:10

Arash Motamedi


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
like image 37
Róisín Grannell Avatar answered Oct 19 '22 17:10

Róisín Grannell