6

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.

talles
  • 14,356
  • 8
  • 45
  • 58

2 Answers2

11

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.

Chris Heald
  • 61,439
  • 10
  • 123
  • 137
0

I think this is not a problem. At least alert(-0 == 0) returns true. I guess if there is one bit used for the sign this bit can also be set if the value is 0. Hovever, it remains the same number.

bweber
  • 3,772
  • 3
  • 32
  • 57