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,

1 var str = 'posterous';
2  
3 if ( str.search('t') >= 0 ) {
4 // character t found
5 }
6 else{
7 // not found
8 }

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

1 var str = 'posterous';
2  
3 if ( !~str.search('t') ) {
4 // character 't' not found branch
5 }
6 else{
7 // found branch
8 }

 

原帖地址:http://www.javascriptturnsmeon.com/the-tilde-operator-in-javascript/
posted @ 2014-10-13 14:45  鍒樻爧  阅读(388)  评论(0编辑  收藏  举报