How to determine if a NaN value is without using isNaN that has false positives?

How to check if an input value is NaNor not without using a function isNaN?

+5
source share
2 answers

If you can use ECMAScript 6 , you Object.is:

return Object.is(obj, NaN);

Otherwise, this is one of the options from underscore.js source code :

// Is the given value `NaN`?
_.isNaN = function(obj) {
  // `NaN` is the only value for which `===` is not reflexive.
  return obj !== obj;
};

Also their note for this function:

Note: this is not the same as the nativeNaN function, which will also return true if the variable is undefined.

+7
source

Convert the input to a number and check if the subtraction is zero:

var x = 'value';
var is_NaN = +x - x !== 0; // The + is actually not needed, but added to show
                           // that a number conversion is made.
+1
source

All Articles