3

I've seen code like this

 v = Math.random() * 100 | 0;

What does the | 0 mean?

gman
  • 100,619
  • 31
  • 269
  • 393

1 Answers1

4

value | 0 means "convert value to an integer"

| is the bitwise OR operator.

To work it first converts the values on both sides to signed 32bit integers then it does a bitwise OR of the values. Since bitwise OR with 0 does nothing this has the effect of just converting to an integer.

It is different that Math.floor in that it converts toward zero

          | Math.floor | Math.ceil | Math.trunc | | 0  |
----------+------------+-----------+------------+------+
   2.5    |     2      |     3     |     2      |   2  |
----------+------------+-----------+------------+------+
   1.5    |     1      |     2     |     1      |   1  |
----------+------------+-----------+------------+------+
   0.5    |     0      |     1     |     0      |   0  |
----------+------------+-----------+------------+------+
  -0.5    |    -1      |     0     |     0      |   0  |
----------+------------+-----------+------------+------+
  -1.5    |    -2      |    -1     |    -1      |  -1  |
----------+------------+-----------+------------+------+
  -2.5    |    -3      |    -2     |    -2      |  -2  |
----------+------------+-----------+------------+------+
 Infinity |  Infinity  |  Infinity |  Infinity  |   0  |
----------+------------+-----------+------------+------+
   NaN    |    NaN     |    NaN    |    NaN     |   0  |
----------+------------+-----------+------------+------+
 2**32+5  | 4294967301 |4294967301 | 4294967301 |   5  |
----------+------------+-----------+------------+------+

That last one, 2*32+5 is a value that does not fit in 32 bits to point out you need to know when | 0 is appropriate and when it's not.

| 0 is also significantly faster than Math.floor or Math.ceil. There may be many reasons it's faster the most obvious is it's an operator, not a function on the Math object which can be replaced and therefore has to be checked on each usage.

It has a very low precedence which means you can usually tack it on to the end of an expressions without parenthesis

 integerResult = someValue / someOtherValue | 0;
gman
  • 100,619
  • 31
  • 269
  • 393
  • can you compare it to `int = ~~n`? is it the same? the same on negatives? thanks! – dandavis May 08 '17 at 04:10
  • Well `~~v` is 2 operations where as `v | 0` is one operation. `| 0` is used extensively in `asm.js` so maybe it has been optimized though that's just speculation. But yea, ~~ seems to generate the same results. ~~ also requires parens `~~50/7` doesn't work where as `50/7|0` does – gman May 08 '17 at 04:13