Search code examples
javascriptinteger

Why is an integer returned when disjunction is used with Math.random()?


I use Math.random() * 10 to get a number between 0 and 10. However, when I use that with disjunction (|), the returned value becomes an integer even though I do not use such methods as Math.floor().

let n = Math.random() * 10;
// n is very likely a decimal number.

let n = Math.random() * 10 | 20;
// n becomes an integer.

Solution

  • | is the bitwise OR operator and when applied to numbers, it first converts both operands to 32-bit integers.