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:

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

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