The tilde ( ~ ) operator in JavaScript

From the JavaScript Reference on MDC,

~ (Bitwise NOT)

Performs the NOT operator on each bit. NOT a yields the inverted value (a.k.a. one’s complement) of a. The truth table for the NOT operation is:

a NOT a
0 1
1 0

Example:

9 = 00000000000000000000000000001001 (base 2)
               --------------------------------
~9 = 11111111111111111111111111110110 (base 2) = -10 (base 10)

Bitwise NOTing any number x yields -(x + 1). For example, ~5 yields -6.

Now lets look at the Logical NOT(!)

! (Logical NOT)

Returns false if its single operand can be converted to true; otherwise, returns true. 

Mixing the two NOT operators together can produce some interesting results:

!~(-2) = false

!~(-1) = true

!~(0) = false

!~(1) = false

!~(2) = false

For all integer operands except -1, the net operand after applying the ~ operator for the ! operator would be truthy in nature resulting in FALSE.

-1 is special because ~(-1) gives 0 which is falsy in JavaScript. Adding the ! operator gives us the only TRUE.

When to use this special case ?

A lot of times in JavaScript String manipulation, you are required to search for a particular character in a string. For example,

We can use the operators instead of the comparison operators, like this:

06. December 2010 by Rajat
Categories: Uncategorized | 9 comments

Comments (9)

  1. You got an extra ! goin on in the last code.You dont want that.

  2. @Paul Thanks! I realized i had the comments wrong. I flipped them to the right order now.

  3. I love it. I’ll always use it for testing -1 just to mess with people!

    • That really is messing with people.
      I came here because I tried to understand the line:
      if !!~ file.indexOf “…”

  4. Wouldn’t be !~str.search(‘t’) slower (as a boolean operation ath the bottom) than a regular str.search(‘t’) >= 0 ?

  5. Vikstrous, better use !1 it makes every one puzzled ))

  6. In Chromium at least, there doesn’t seem to be any difference in performance between Numeric comparison and a bitwise NOT:http://jsperf.com/indexof-numeral-vs-bitwise-notIt's quite a nice little trick, you can also use it as a faster Math.floor (though it works slightly differently for negative Numbers – they approach zero rather than negative infinity) by using two of them, since any floats/doubles are truncated when using a bitwise operation:~~1.999 === 1~~-1.999 === -1You can also use a bitwise OR against zero to achieve the same effect as a double bitwise NOT1.999 | 0 === 1-1.999 | 0 === -1though this can look like you made a typo when coalescing values

  7. Dude! Awesome! I’ve never used tilda in my code :) Huge like!!

  8. Great article! I remember first seeing the tilde operator in a node library I was using, [here it is in expressjs](https://github.com/visionmedia/express/blob/18453476ad81051d304d04046815238bae9c3cb1/examples/mvc/lib/boot.js#L28)

Leave a Reply

Required fields are marked *