0

In Kyle Simson's book You Don't Know JS,

You can also implement polyfills more simply by applying uniqueness that NaN does not equal to itself. NaN is the only value in all languages of the world "any value other than self is always equal to you."

The polyfill of the function isNaN is proposed as follows.

// polyfill NaN
if (!Number.isNaN) {
  Number.isNaN = function(n) {
    return n !== n;
  };
}

However, is the code n! == n always forced tofalse? (Actually, it was the same when I made the function simple and executed it)

So I don't understand what the code means.

I would be grateful if you could explain this.

redchicken
  • 311
  • 1
  • 5
  • 18

1 Answers1

2

NaN is the only value in Javascript which, when compared against itself with ===, produces false (or, equivalently, when compared against itself with !==, returns true). Any other value, when checked against itself with ===, will return true.

NaN !== NaN // true
const obj = {};
obj !== obj     // false
0 !== 0         // false
'foo' !== 'foo' // false
// etc, everything else other than NaN
// will produce: // false

So

return n !== n;

is a reliable check of whether n is NaN.

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320