How to: The ~ operator?

I can’t google the ~ operator to find out more about it. Can someone please explain to me in simple words what it is for and how to use it?

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).

One usage of the ~ (Tilde) I have seen was getting boolean for .indexOf().

You could use: if(~myArray.indexOf('abc')){ };

Instead of this: if(myArray.indexOf('abc') > -1){ };

JSFiddle Example

Additional Info: The Great Mystery of the Tilde(~)

Search Engine that allows special characters: Symbol Hound

It’s a tilde and it is the bitwise NOT operator.

~ is a bitwise NOT operator. It will invert the bits that make up the value of the stored variable.

The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .
Read More:   Start script missing error when running npm start

Similar Posts