74

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?

GOTO 0
  • 42,323
  • 22
  • 125
  • 158
  • 8
    Mixing `||` and `&&` without some parentheses is extremely ugly and confusing. – ThiefMaster Jan 22 '12 at 22:42
  • 12
    `NaN` and `NaN` are supposed to be unequal for a reason, because, for example, `0/0` and `parseInt("not a number!")`, while they both evaluate to `NaN`, should not be considered equal. – Peter Olson Jan 22 '12 at 22:44
  • 2
    @Peter sometimes this difference is irrelevant to the algorithm. I think this is the case of the OP. – drigoangelo Feb 28 '14 at 13:11

11 Answers11

53
if(val1 == val2 || (isNaN(val1) && isNaN(val2)))

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

ThiefMaster
  • 310,957
  • 84
  • 592
  • 636
26

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
michaelbahr
  • 4,837
  • 2
  • 39
  • 75
davidchambers
  • 23,918
  • 16
  • 76
  • 105
  • 1
    `undefined` becomes `NaN` when converted to a `Number` anyway ... imo it's much better to know that during the `isNaN` phase than after. – Esailija Jan 22 '12 at 23:13
  • 10
    What's wrong with `isNaN(undefined)` being `true`? `undefined` **isn't a number**. What seems to be so misleading here for you? – trejder Jul 18 '13 at 07:39
  • 7
    @trejder: NaN and undefined are different values. Different value *types*, even. – davidchambers Jul 22 '13 at 17:25
  • 5
    @davidchambers: True. Which doesn't change the fact, that `undefined` *isn't* a number. Which leads us to a conclusion, that `isNaN(undefined)` *should* return `true`. The fact, that `NaN` and `undefined` are different values and different value types, doesn't change my state. As this is whole different story. Or point me out, where I'm wrong. – trejder Jul 23 '13 at 08:05
  • 5
    @trejder: We have different ideas as to which question isNaN should answer. You believe `isNaN(x)` should be equivalent to `!isNumber(x)`, whereas I suggest it should tell us whether the value of x is precisely NaN. If one wants to know whether a value is not a number, `Object.prototype.toString.call(x) !== '[object Number]'` is preferable as it doesn't allow for competing interpretations. – davidchambers Jul 30 '13 at 18:19
  • `0/0` and `"hello world"` are also different value *and* different value types and both `isNaN(0/0)` and `isNaN("hello world")` return `true` and I can't think of any reason one would want it to be otherwise – drigoangelo Feb 28 '14 at 13:05
  • 2
    @drigoangelo: If you're comfortable writing `if (x !== x)` and have confidence that all current and future members of your team will understand what that does, great. If not, it would be nice to have a function which answers the question: _Is this value NaN?_ Unfortunately the built-in isNaN is not that function. – davidchambers Feb 28 '14 at 18:10
  • That's why we have references: To know what the meaning of a function is, and not what we guess, it is. – Jochen Oct 29 '20 at 12:50
23

Try using Object.is(), it determines whether two values are the same value. Two values are the same if one of the following holds:

  • both undefined
  • both null
  • both true or both false
  • both strings of the same length with the same characters in the same order
  • both the same object
  • both numbers and
    • both +0
    • both -0
    • both NaN
    • or both non-zero and both not NaN and both have the same value

e.g. Object.is(NaN, NaN) => true

Refer to https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is

GOTO 0
  • 42,323
  • 22
  • 125
  • 158
Anant
  • 342
  • 6
  • 14
  • Good answer for modern javascript. Just take care because `0 === -0` returns `true` but `Object.is(0, -0)` returns `false`. For the asker's use case you might need to do `val1 === val2 || Object.is(val1, val2)`. – Michael Kropat Oct 01 '18 at 19:33
  • never knew about this +1. Thanks – pariola Dec 29 '18 at 23:20
5

if ( val1 === val2 )

If either one or both are NaN it will evaluate to false.

Also, NaN !== NaN

Esailija
  • 138,174
  • 23
  • 272
  • 326
5

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.

Joachim Isaksson
  • 176,943
  • 25
  • 281
  • 294
5

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. :)

Grace Huang
  • 5,355
  • 5
  • 30
  • 52
  • 1
    It won't always give an identical result to the original code, but then again, in the cases where it would vary, it may be a preferred behavior. For example `" " == 0;`, which is `true`, but will be `false` with your code. This may be considered an improvement. –  Jan 22 '12 at 23:22
4

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

mario ruiz
  • 880
  • 1
  • 11
  • 28
2

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

Community
  • 1
  • 1
dopeddude
  • 4,943
  • 3
  • 33
  • 41
-1

Why not an if statement like this?

if (isNaN(x) == true){
        alert("This is not a number.");
    }
Pauline Orr
  • 123
  • 1
  • 13
-1

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

Community
  • 1
  • 1
-1

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;
}