The tilde ( ~ ) operator in JavaScript
From the JavaScript Reference on MDC,
~ (Bitwise NOT)
Performs the NOT operator on each bit. NOT
ayields the inverted value (a.k.a. one’s complement) ofa. 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:
You got an extra ! goin on in the last code.You dont want that.
@Paul Thanks! I realized i had the comments wrong. I flipped them to the right order now.
I love it. I’ll always use it for testing -1 just to mess with people!
Wouldn’t be !~str.search(‘t’) slower (as a boolean operation ath the bottom) than a regular str.search(‘t’) >= 0 ?
Vikstrous, better use !1 it makes every one puzzled ))
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