20

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?

muudless
  • 6,744
  • 7
  • 34
  • 56
  • a good place to learn more about it is [Google Tech Talk](http://www.youtube.com/user/GoogleTechTalks?) then search for javascript – Ibu Jun 07 '11 at 04:09

4 Answers4

25

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

David Tang
  • 86,742
  • 28
  • 159
  • 145
  • 7
    Pretty obvious, but for anyone interested, (I think) the technical term for "chopping off" would be "truncating." Using the double bitwise not for this purpose is probably faster and use less memory than `Math.floor`, but the resulting number would still use the same amount of memory since JavaScript makes no distinction between integers, floats, etc. for numerical values. – Cristian Sanchez Jun 07 '11 at 04:40
3

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

Justin
  • 22,998
  • 16
  • 104
  • 122
1

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

Nik
  • 6,733
  • 11
  • 49
  • 79
1

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

http://en.wikipedia.org/wiki/Bitwise_operations_in_C#Bitwise_NOT_.22.7E.22_.2F_one.27s_complement_.28unary.29

Babak Naffas
  • 11,532
  • 3
  • 32
  • 48