Why does a shift by 0 truncate the decimal?

You’re correct; it is used to truncate the value.

The reason >> works is because it operates only on 32-bit integers, so the value is truncated. (It’s also commonly used in cases like these instead of Math.floor because bitwise operators have a low operator precedence, so you can avoid a mess of parentheses.)

And since it operates only on 32-bit integers, it’s also equivalent to a mask with 0xffffffff after rounding. So:

0x110000000      // 4563402752
0x110000000 >> 0 // 268435456
0x010000000      // 268435456

But that’s not part of the intended behaviour since Math.random() will return a value between 0 and 1.

Also, it does the same thing as | 0, which is more common.

Leave a Comment