According to this post, run the following codes
> ~function () { console.log('foo');}()
  foo
  -1
As we all know, the return value of the above anonymous function is undefined. Why ~undefined is -1? I couldn't find any similar question.
According to this post, run the following codes
> ~function () { console.log('foo');}()
  foo
  -1
As we all know, the return value of the above anonymous function is undefined. Why ~undefined is -1? I couldn't find any similar question.
~ is bitwise NOT. It uses ToInt32 to convert the argument to a number. ToInt32 is defined as:
- Let number be ToNumber(argument).
- ReturnIfAbrupt(number).
- If number is NaN, +0, −0, +∞, or −∞, return +0.
...
In turn, ToNumber(undefined) returns NaN, so according to step 3, ToInt32 returns 0.
And ~0 is -1.
 
    
    every thing that cannot be represented in bits in JS for example "undefined, NaN" is treated a 0 or 0000000000000b for the ~ operator since it converts the operand into an signed integer see @felixkling answer for more details on this and since the operation ~ is BITwise not or 1s complement which flips the bits so the statement results in 111111111111b as a sequence of 1 and when dealing in numbers on binary level the MSB(most significant bit) is treated as a sign so when converting all the 0s to 1s it results in decimal value of -1 try ~0 for instance. and use this code to get the binary representation of a number (-3 >>> 0).toString(2)) 
Apparently the bit representation of undefined is all 0s. This can be seen if by the following: undefined | 0 which evaluates to 0. Because of this we know that undefined's bit representation is all zeros.
If we now filp all bits (wich is exactly what ~ does) we get all 1s which is the representation of -1.
All this works because of javascript's type cohersion
