A shorter way to do Math.floor – A little known trick

Nothing groundbreaking, but someone just handed me code that was filled with Math.floor calls. While this doesn’t automatically slow down your code the way it used to, thanks to better Javascript engines, it’s still ugly as hell to look at.

Now, those people who like to put wavy brackets on individual lines will probably start shouting again, but once you’ve gotten used to it, this is actually a good deal more readable, since it shortens the code considerably, while still having a “unique look” that you’ll be able to identify quickly

Instead of
Math.floor(foo)

You can simply do a bitwise OR with 0:
0|(foo)

The reason this works is that any bit operation causes the number to be converted to a signed 32 bit integer. While this isn’t strictly the same as what Math.floor does, it will give you the same result at least for positive 31 bit integers. For negative ones you get something a little different (but typically far more useful), namely the integer part (-3 for -3.7) instead of the the highest integer smaller or equal to the given number (-4 for -3.7).