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 |
Equality comparison with NaN always results in False
.
We can go for the javascript function isNaN()
for checking equality with NaN.
Example:
1. isNaN(123) //false
2. var array = [3, NaN];
for(var i = 0 ; i< array.length; i++){
if(isNaN(array[i])){
console.log("True ---- Values of " + i);
} else {
console.log("false ---- Values of " + i);
}
}
Results:
false ---- Values of 0
True ---- Values of 1
For Numeric cases the solution is fine but to extend it to work for other data-types as well my suggestion would be as follows:
if(val1 === val2 || (val1 !== val1 && val2 !== val2))
Reason being global isNaN
is erroneous. It will give you wrong results in scenarios like
isNaN(undefined); // true
isNaN({}); // true
isNaN("lorem ipsum"); // true
I have posted a comprehensive answer here which covers the NaN comparison for equality as well.
How to test if a JavaScript variable is NaN
if(val1 == val2 || (isNaN(val1) && isNaN(val2)))
Nothing to improve. Just add the parentheses to make it clear to everyone.
And what's about the function Number.isNaN() ? I believe this must be used whenever is possible.
> NaN === NaN
false
> Number.isNaN
ƒ isNaN() { [native code] }
> Number.isNaN() === Number.isNaN()
true
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/isNaN
if ( val1 === val2 )
If either one or both are NaN
it will evaluate to false.
Also, NaN !== NaN
I created this answer after reviewing the suggestions of ThiefMaster, Esailija, Joachim Isaksson and davidchambers. Can this be further improved?
// Determines if two numeric values are equal.
// Also returns true when both parameters are NaN.
function areEqualNumeric(val1, val2) {
return val1 === val2 || (val1 !== val1 && val2 !== val2);
}