0

Just saw the code below for generating a random number with a range. But I don't quite understand the part that uses |. What does that do? How does that affect an integer return vs a normal floating number?

function rand(min, max, integer) {
 var r = Math.random() * (max - min) + min; 
 return integer ? r|0 : r;
}
Kelvin Zhao
  • 2,243
  • 3
  • 22
  • 31
  • https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators#Bitwise_OR – Andrew Li Apr 29 '17 at 04:53
  • 1
    It's like `Math.floor(r)` but shorter. – Ja͢ck Apr 29 '17 at 04:57
  • this is a bitwise or – JYoThI Apr 29 '17 at 04:59
  • 2
    Ugh, cryptic abuse of integer coercion. I'd rather use Math.floor – slebetman Apr 29 '17 at 05:00
  • JavaScript truncates any non-integer numbers in bitwise operations, so its computed as 0|0, which is 0 – JYoThI Apr 29 '17 at 05:03
  • 1
    No, not exactly,@Ja͢ck. Even in this specific case, `r|0` is more like `r => r<0? Math.ceil(r): Math.floor(r)` And that snippet doesn't even cover dealing with `Infinity` or `NaN` or more widely, type conversion by the bit-operator wich has slightly different rules than the regular conversion to a Number. – Thomas Apr 29 '17 at 05:11

0 Answers0