JS Tip of the Day: Negative Zero

Negative Zero
Version ES2015 (Object.is)
Level: Intermediate

Numbers in JavaScript are stored as double-precision values specified by the IEEE 754 standard. In this format, like every other number value, 0 can be negative. So just as you can have a 1 and a -1, so too can you have a 0 and a -0.

For the most part, 0 and -0 are equivalent. Numerically they have the same value, and if you attempt to compare them, even with strict equality, they’ll appear as equal.

console.log(0 === -0); // true

There are only a few operations that will expose the difference of 0 and -0, such as dividing a number by 0. The result will be infinity, but depending on the sign of the 0, it could be negative or positive infinity.

console.log(1/0); // Infinity
console.log(1/-0); // -Infinity

If you need to see if a 0 is negative or not, instead of using normal comparison, you can use Object.is() which can differentiate between 0 and -0.

console.log(Object.is(0, 0)); // true
console.log(Object.is(-0, -0)); // true
console.log(Object.is(0, -0)); // false

You’ll only see negative 0 with regular number values in JavaScript. The other numeric type, BigInt, does not support them. A negative BigInt 0 is the same as a positive BigInt 0.

console.log(Object.is(0n, -0n)); // true

More info: