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 |
Avoid isNaN
. Its behaviour is misleading:
isNaN(undefined) // true
_.isNaN
(from Underscore.js) is an elegant function which behaves as expected:
// Is the given value `NaN`?
//
// `NaN` is the only value for which `===` is not reflexive.
_.isNaN = function(obj) {
return obj !== obj;
};
_.isNaN(undefined) // false
_.isNaN(0/0) // true
NaN is never equal to itself no matter the comparison method, so the only more concise solution for your problem that I can think of would be to create a function call with a descriptive name for doing this rather special comparison and use that comparison function in your code instead.
That would also have the advantage of localizing changes to the algorithm the day you decide that undefined should be equal to undefined too.
Why not an if statement like this?
if (isNaN(x) == true){
alert("This is not a number.");
}
Found another way using Array.prototype.includes MDN link. Apparently, [NaN].includes(NaN) returns true for NaN.
function IsActuallyNaN(obj) {
return [obj].includes(NaN);
}
Or we can go with davidchambers' solution which is much simpler.
function IsActuallyNaN2(obj) {
return obj !== obj;
}
Try using Object.is()
, it determines whether two values are the same value. Two values are the same if one of the following holds:
undefined
null
true
or both false
+0
-0
NaN
NaN
and both have the same valuee.g. Object.is(NaN, NaN)
=> true
Refer to https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is
As long as you know these two variables are numeric, you can try:
if (val1 + '' == val2 + '')
It turns the two values into strings. A funny answer, but it should work. :)