Select theme

Math.floor() and ~~

Published by on

Using the bitwise operators in JavaScript you can do all kinds of interesting things.

For example, it is possible to use the operator "bitwise negation" (the tilde ~) to round off numbers:

Using the bitwise operators in JavaScript you can do all kinds of interesting things.

For example, it is possible to use the operator "bitwise negation" (the tilde ~) to round off numbers:

It is helpful because rounding a number using the "bitwise negation" operator is much faster in many browsers than using Math.floor.

This feature is especially useful when rounding a number has to be repeated very often, such as when manipulating the pixel data of a <canvas> element where several thousand pixels have to be compared one by one.

Since I use exactly this use case in my projects (see for example glitch-canvas, I have used ~~ as a replacement for Math.floor() in general.

This was a mistake.

Because there are numbers for which the results of ~~ and Math.floor() not match:

It is helpful because rounding a number using the "bitwise negation" operator is much faster in many browsers than using Math.floor.

This feature is especially useful when rounding a number has to be repeated very often, such as when manipulating the pixel data of a <canvas> element where several thousand pixels have to be compared one by one.

Since I use exactly this use case in my projects (see for example glitch-canvas, I have used ~~ as a replacement for Math.floor() in general.

This was a mistake.

Because there are numbers for which the results of ~~ and Math.floor() not match:

Many shortcuts and hacks in code are helpful for special cases, but they should be used with caution and not generalized. That is why they are called shortcuts and hacks.

I learned something today, hope you did as well. Until next time!