For numerical cases, the solution is fine, but for expanding it to work with other data types, my suggestion will be as follows:
if(val1 === val2 || (val1 !== val1 && val2 !== val2))
The cause of the global isNaN is erroneous. This will give you incorrect results in scenarios like
isNaN(undefined); // true isNaN({}); // true isNaN("lorem ipsum"); // true
I have posted a comprehensive answer here that also covers NaN comparisons for equality.
How to check if JavaScript variable is NaN
dopeddude Aug 21 '15 at 10:32 2015-08-21 10:32
source share