Comparing NaN values for equality in Javascript

I need to compare two numeric values for equality in Javascript. The values may be NaN as well. I've come up with this code:

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

which is working fine, but it looks bloated to me. I would like to make it more concise. Any ideas?


Solution 1:

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

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

Solution 2:

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