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?
Unlike all other possible values in JavaScript, it is not possible to use the equality operators (== and ===) to compare a value against NaN to determine whether the value is NaN or not, because both NaN == NaN and NaN === NaN evaluate to false . The isNaN() function provides a convenient equality check against NaN .
Check for NaN with self-equality In JavaScript, the best way to check for NaN is by checking for self-equality using either of the built-in equality operators, == or === . Because NaN is not equal to itself, NaN != NaN will always return true .
The isNaN() method returns true if a value is NaN. The isNaN() method converts the value to a number before testing it.
The main difference between the == and === operator in javascript is that the == operator does the type conversion of the operands before comparison, whereas the === operator compares the values as well as the data types of the operands.
if(val1 == val2 || (isNaN(val1) && isNaN(val2)))
Nothing to improve. Just add the parentheses to make it clear to everyone.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With