Why does
(Math.random() * 16) | 0
give me a number between 0 and 15 inclusive? That is, what is the |
doing to the floating point coming out of Math.random()
?
Why does
(Math.random() * 16) | 0
give me a number between 0 and 15 inclusive? That is, what is the |
doing to the floating point coming out of Math.random()
?
I’m not a JavaScript pro on my own, but it seems as if the bitwise or and automatic type coercion is used here to truncate the float
| 0
is a way in Javascript to quickly convert a number to an integer.
Fun fact: before WebAssembly became what it is today, they tried to make Javascript the “assembly” language, before they decided otherwise. That “assembly Javascript” was known as Asm.js and they abused the | 0
notation. The Code generation section of the previous Wikipedia page is an interesting read about this:
Note the addition of
|0
and the lack of type specifiers. In JavaScript, bitwise operators convert their operands to 32-bit signed integers and give integer results. This means that a bitwise OR with zero converts a value to an integer (a very simple “conceptual” presentation of bitwise operators may not deal with type conversion at all, but every programming language defines operators for its own convenience, as Javascript does here)
Everything above is right but with the addition that there is no integer type (other than bigint
) in JavaScript, so the result is still a float (number
in js), but truncated, like @NobbZ said.