Reputation: 48367
~(function () {}).toString();
is absolutely valid JavaScript syntax and I saw that it returns -1
.
I know that ~
is not operator. For instance ~5
=~0101
which means 1010
in base 2 and 10
in decimal.
console.log(~(function () {}).toString());
But what is the explanation in this situation ?
Maybe ~NaN
returns -1
.
Upvotes: 2
Views: 92
Reputation: 68393
As per spec
Let oldValue be ToInt32(GetValue(expr)).
Number((function () {}).toString();)
-> Number("function () {}")
-> NaN
Again as per spec
If number is NaN, +0, −0, +∞, or −∞, return +0.
so ~NaN
amounts to ~0
which is -1
Upvotes: 2
Reputation: 167182
Taken from this blog: The Great Mystery of the Tilde(~):
The tilde is an operator that does something that you’d normally think wouldn’t have any purpose. It is a unary operator that takes the expression to its right performs this small algorithm on it (where N
is the expression to the right of the tilde): -(N+1)
. See below for some samples.
console.log(~-2); // 1
console.log(~-1); // 0
console.log(~0); // -1
console.log(~1); // -2
console.log(~2); // -3
Upvotes: 1