2

~Infinity my question is how it evaluate to -1.

~Infinity= -1

console.log(~Infinity);

because

Infinity+Infinity=Infinity

console.log(Infinity+Infinity)

or

Infinity-Infinity = NaN

console.log(Infinity-Infinity)

How ~Infinity output is coming to -1;

j08691
  • 204,283
  • 31
  • 260
  • 272
Nits
  • 520
  • 6
  • 21
  • 2
    http://stackoverflow.com/questions/12299665/what-does-a-tilde-do-when-it-precedes-an-expression – j08691 Jun 17 '16 at 13:13
  • 2
    Bitwise operators truncate the operands to 32bit integers. And it so happens that truncating the value `Infinity` results in `0` (`Infinity | 0`). `~0` is `-1`. – Felix Kling Jun 17 '16 at 13:14
  • @j08691 Interesting, but neither the question nor the answers seem to address OP's issue there. – Kyll Jun 17 '16 at 13:15

1 Answers1

6

In IEEE 754 floating point, the Infinity constant is represented by a value with all the fraction bits set to 0. When that's coerced to a 32-bit integer value in calculating the bitwise complement (the ~ unary operator), you get just zero, so the complement is all 1 bits, or -1.

Positive infinity is:

01111111111100000000000000000000000000000000000000000000000000000

(give or take a zero). The sign bit is 0, the exponent is all 1 bits, and the mantissa is all zeros.

Pointy
  • 405,095
  • 59
  • 585
  • 614
  • 1
    It'd be cool to see the binary representation to get a clear idea of what's happening. – Kyll Jun 17 '16 at 13:17