How to: The ~ operator?

It is a bitwise NOT.

Most common use I’ve seen is a double bitwise NOT, for removing the decimal part of a number, e.g:

var a = 1.2;
~~a; // 1

Why not use Math.floor? The trivial reason is that it is faster and uses fewer bytes. The more important reason depends on how you want to treat negative numbers. Consider:

var a = -1.2;
Math.floor(a); // -2
~~a; // -1

So, use Math.floor for rounding down, use ~~ for chopping off (not a technical term).

Leave a Comment