Search code examples
javascriptnegative-numberunary-operator

Negative zero in JavaScript?


I've just noticed that I can do the following in JavaScript:

var z = -0;
console.log(z); // prints -0

Why does the unary negation works on zero?

Is this one of the many JavaScript quirks or it does (somehow) have a purpose?


P.S.:

It seems to be happening on Firefox 38.0a2 and Chrome 41.0.2272. On Node.js v0.10.36 doesn't happen. Dunno about IE.


Solution

  • You've just encountered the signed zero.

    The IEEE 754 standard for floating-point arithmetic (presently used by most computers and programming languages that support floating point numbers) requires both +0 and −0. Real arithmetic with signed zeros can be considered a variant of the extended real number line such that 1/−0 = −∞ and 1/+0 = +∞; division is only undefined for ±0/±0 and ±∞/±∞.

    All numbers in Javascript are floating-point, so zeros must be signed.