0

a = [1, 2, NaN];

for (const item of a) {
    if (item === NaN) {
        console.log(true);
    }
}

I want to be able to print true to the console. Why can't item match up to NaN?

tonitone110
  • 139
  • 6
  • 2
    Does this answer your question? [What is the rationale for all comparisons returning false for IEEE754 NaN values?](https://stackoverflow.com/questions/1565164/what-is-the-rationale-for-all-comparisons-returning-false-for-ieee754-nan-values) – ASDFGerte Jul 01 '20 at 16:34
  • Because `NaN` equals nothing, even not itself. Don't ask me why though :) – sp00m Jul 01 '20 at 16:39
  • 1
    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/NaN. NaN === NaN always returns false. isNaN(NaN) will return true. – DynasticSponge Jul 01 '20 at 16:39
  • And while the question is asking for "why", i think this may be more catered towards what is actually desired: [how-do-you-check-that-a-number-is-nan-in-javascript](https://stackoverflow.com/questions/2652319/how-do-you-check-that-a-number-is-nan-in-javascript). That topic however is a bit old, and i am unsure, whether the top answers have references to [Number.isNaN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isNaN), which is often preferrable. – ASDFGerte Jul 01 '20 at 16:43

2 Answers2

2

Hilariously, in javascript NaN does not equal NaN. That means that you can check for NaN by doing if(foo !== foo). Normally you should use the isNan() function instead of that because it's way more readable.

Charlie Bamford
  • 1,268
  • 5
  • 18
  • Logically it kinda makes sense. If `(foo !== foo)` then its apparently not a number. I think the NaN being left without its "history" on how it became at this state, is why it makes sense. For example `1/0` is NaN but when assigned to a variable, the "history" is lost and thus is not comparable to another NaN with a different "history". – GetSet Jul 01 '20 at 16:43
0

Because NaN is the only thing in Javascript not equal to itself. isNaN()

a = [1, 2, NaN];

for (const item of a) {
    if (isNaN(item)) {
        console.log(true);
    }
}
Himanshu Pandey
  • 688
  • 2
  • 8
  • 15