Comparing NaN values for equality in Javascript

Try using Object.is(), it determines whether two values are the same value. Two values are the same if one of the following holds:

  • both undefined
  • both null
  • both true or both false
  • both strings of the same length with the same characters in the same order
  • both the same object
  • both numbers and
    • both +0
    • both -0
    • both NaN
    • or both non-zero and both not NaN and both have the same value

e.g. Object.is(NaN, NaN) => true

Refer to https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is


if ( val1 === val2 )

If either one or both are NaN it will evaluate to false.

Also, NaN !== NaN


if(val1 == val2 || (isNaN(val1) && isNaN(val2)))

Nothing to improve. Just add the parentheses to make it clear to everyone.


Avoid isNaN. Its behaviour is misleading:

isNaN(undefined) // true

_.isNaN (from Underscore.js) is an elegant function which behaves as expected:

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

_.isNaN(undefined) // false
_.isNaN(0/0) // true