3

I normally use the double bitwise NOT (~~) as an alternative to Math.floor. Recently I found out that, when used with NaN, it will return 0:

console.log(~~NaN)

After some investigation I found out that, according to the ECMAScript 2015 specs, the bitwise NOT uses ToInt32 internaly...

Let oldValue be ToInt32(GetValue(expr)).

... which, by its turn:

If number is NaN, +0, −0, +∞, or −∞, return +0.

That explains the sequence in my snippet: ~~NaN --> ~~0 --> ~-1 --> 0. However, to me, 0 seems to be an odd choice for NaN.

My question: why did the specification choose 0 as the returned value of ToInt32(NaN)? One could say "because NaN is falsy", but that's not the case of +∞ or −∞. I'm preferably looking for some documented ECMA explanation (which therefore would not be opinion based).

3
  • 2
    Because bitwise operators only work with integers, and NaN is a float.
    – Barmar
    Oct 31, 2019 at 2:31
  • ECMA-262 tells you all you need to know: "The abstract operation ToInt32 converts argument to one of 2^32 integer values…", so it must produce an integer. Even where the argument isn't a number (and hence ToNumber(argument) produces NaN), it returns 0. This is the wrong place to ask why, better to try the TC39 mailing list or ES Discuss.
    – RobG
    Oct 31, 2019 at 3:55
  • "However, to me, 0 seems to be an odd choice for NaN" What other value would be less odd?? -1? +1? -2**31 or +2**31-1? All seem rather arbitrary. There's no saner choice than 0.
    – Boann
    Oct 31, 2019 at 15:53

1 Answer 1

2

NaN is generally a floating-point concept, not an integer one. (Same with negative zero and the infinities. JavaScript numbers are IEEE floats.) ToInt32 produces only integers from −2**31 to 2**31−1, like you’d expect to see in a 32-bit integer type in most other languages.

1
  • 2
    "Negative zero and the infinities" would be a great band name.
    – kshetline
    Oct 31, 2019 at 3:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.