In the accepted answer on my earlier question
( What is the fastest way to generate a random integer in javascript? ), I was wondering how a number loses its decimals via the symbol |
.
For example:
var x = 5.12042;
x = x|0;
How does that floor the number to 5
?
Some more examples:
console.log( 104.249834 | 0 ); //104
console.log( 9.999999 | 0 ); // 9
Because, according to the ECMAScript specifications, bitwise operators call ToInt32
on each expression to be evaluated.
See 11.10 Binary Bitwise Operators:
The production
A : A @B
, where@
is one of the bitwise operators in the productions above, is evaluated as follows:
Evaluate
A
.Call
GetValue(Result(1))
.Evaluate
B
.Call
GetValue(Result(3))
.Call
ToInt32(Result(2)).
Call
ToInt32(Result(4)).
Apply the bitwise operator
@
toResult(5)
andResult(6)
. The result is a signed 32 bit integer.Return
Result(7)
.