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?
Bitwise operators work on integers only.
Infinityis 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: