Comparing NaN values for equality in Javascript

GOTO 0 picture GOTO 0 · Jan 22, 2012 · Viewed 51.6k times · Source

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?

Answer

ThiefMaster picture ThiefMaster · Jan 22, 2012
if(val1 == val2 || (isNaN(val1) && isNaN(val2)))

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