4 ms·
In JavaScript: (NaN === NaN) is false (NaN !== NaN) is true
by niyazpk 15y ago
In JavaScript:
(NaN === NaN) is false
(NaN !== NaN) is true
- raganwald 15y agoThis is isomorphic to NULLs in some languages (I think SQL behaves this way). Basically, NaN isn’t some specific thing, it’s an indication of something that isn’t a number. So two things that aren’t numbers can’t be thought to be equal to each other, they might be radically different things. If there’s a WTF, it’s that NaN === NaN is either true or false. If I were writing a language, it might be undecideable. But if you end up with: Undecideable === Undecideable //=> Undecideable You are opening up the “Hopelessly Egocentric Null” can of worms: https://github.com/raganwald/homoiconic/blob/master/2009-02-02/hopeless_egocentricity.md https://github.com/raganwald/homoiconic/blob/master/2009-02-...
- masklinn 15y ago> I think SQL behaves this way Yes. It's also how NaNs are supposed to work according to IEEE-754. The only reason why it can be strange in javascript is that it's pretty common to encounter nans in JS as the language tries very hard not to throw errors and likes nans a lot (so `parseInt('foo')` returns NaN instead of `null` or an error), whereas it's very rare in other languages. Pretty much all languages have nans, and all nans behave this way. Here it is in Python: >>> float('nan') nan >>> float('nan') == float('nan') False >>> float('nan') != float('nan') True >>> a = float('nan') >>> a == a False >>> import decimal >>> decimal.Decimal('NaN') Decimal('NaN') >>> decimal.Decimal('NaN') == decimal.Decimal('NaN') False >>> a = decimal.Decimal('NaN') >>> a == a False edit: now that I think about it, there is a difference: in SQL, all operations involving `NULL` (including comparisons) return `NULL`, so `NULL = NULL` => `NULL` and `NULL != NULL` => `NULL`.
- chc 15y agoThat's not a JavaScript feature; it's part of the IEEE 754 standard for floating point numbers. NaNs are unordered. Every language that provides standard floating point numbers does it that way.
- shadowfiend 15y agoSpecifically, testing for NaN should be done using the isNaN function, never equality. That's not expounded on as often as necessary, I think heh.
- rimantas 15y agoThis is correct and good. Whats funny, that typeof NaN is "number" :)