Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Negative zero in JavaScript? [duplicate]

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.

like image 201
talles Avatar asked Mar 23 '15 20:03

talles


1 Answers

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.

like image 110
Chris Heald Avatar answered Sep 23 '22 01:09

Chris Heald