Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is ( Infinity | 0 ) === 0?

Tags:

I'm fiddling around with bitwise operators in JavaScript and there is one thing I find remarkable.

The bitwise or operator returns 1 as output bit if one of the two input bits are 1. So doing x | 0 always returns x, because | 0 has no effect:

  • ( 1 | 0 ) === 1
  • ( 0 | 0 ) === 0

However, when I calculated Infinity | 0, I got 0. This is surprising in my opinion, because by the above one should get Infinity. After all, ( x | 0 ) === x.

I cannot find where in the ECMAscript specification this is explicitly defined, so I was wondering what exactly implies that ( Infinity | 0 ) === 0. Is is perhaps the way Infinity is stored in memory? If so, how can it still be that doing a | 0 operation causes it to return 0 whereas | 0 should not do anything?

like image 448
pimvdb Avatar asked Jul 11 '11 12:07

pimvdb


2 Answers

Bitwise operators work on integers only.
Infinity is a floating-point value, not an integer.

The spec says that all operands of bitwise operations are converted to integers (using the ToInt32 operation) before performing the operation.

The ToInt32 operation says:

If number is NaN, +0, −0, +∞ or –∞ return +0.

like image 99
SLaks Avatar answered Oct 25 '22 03:10

SLaks


Doing math and other operations that expect integers with NaN and Infinity is usually a bad idea. How would you set/clear a bit from Infinity?

Actually, bit-wise operations are only defined for integers - and integers do not have NaN or Infinity.

like image 22
ThiefMaster Avatar answered Oct 25 '22 03:10

ThiefMaster