3

Possible Duplicate:
How to: The ~ operator?

What's the ~ operator does in javascript?

input

alert(~1)

output is

-2 

input

~function () {}()

output is

-1

I never heard about ~ operator in javascript

Community
  • 1
  • 1
wukong
  • 2,140
  • 2
  • 20
  • 29

3 Answers3

5

https://developer.mozilla.org/en/JavaScript/Reference/Operators/Bitwise_Operators

Bitwise NOT ~ a Inverts the bits of its operand.

I guess its fairly odd that a function returns -1, but what would you expect anyway.

TJHeuvel
  • 11,562
  • 3
  • 35
  • 46
2

This is the bitwise not operator that inverts the value of every bit in the integer. In binary a signed integer has the following representation:

00000001 = 1
11111110 = -2

See this wikipedia article.

trojanfoe
  • 116,099
  • 18
  • 197
  • 233
1

The bitwise NOT operator (~) will take its operand, convert it to a 32-bit integer, and will invert each bit so that each 0 becomes a 1 and vice versa.

http://james.padolsey.com/javascript/double-bitwise-not/

JohnJohnGa
  • 14,494
  • 15
  • 58
  • 83