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.
A variable that has not been assigned a value is of type undefined . A method or statement also returns undefined if the variable that is being evaluated does not have an assigned value. A function returns undefined if a value was not returned .
The value null represents the intentional absence of any object value. It's never assigned by the runtime. Meanwhile any variable that has not been assigned a value is of type undefined . Methods, statements and functions can also return undefined .
Undefined is also a primitive value in JavaScript. A variable or an object has an undefined value when no value is assigned before using it. So you can say that undefined means lack of value or unknown value. undefined is a token.
~
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With