Search code examples
javascriptcomparisonequalitynan

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

  • 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