2

~(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.

Mihai Alexandru-Ionut
  • 47,092
  • 13
  • 101
  • 128

2 Answers2

2

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

gurvinder372
  • 66,980
  • 10
  • 72
  • 94
1

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
Praveen Kumar Purushothaman
  • 164,888
  • 24
  • 203
  • 252