7

I've notice the expression

(a !== a && b !== b)

in angularjs source code:

compare = function(a, b) { return a === b || (a !== a && b !== b); };

Isn't the expression always resolve to false? what is the reason to write something like this?

avivr
  • 2,573
  • 3
  • 22
  • 34
  • 10
    Not for `NaN`. Wait, I'll dig up the dupe. – Bergi Jun 22 '15 at 13:00
  • @Bergi, got [this](http://stackoverflow.com/q/22266391/464709), not sure it's the duplicate you're looking for. – Frédéric Hamidi Jun 22 '15 at 13:01
  • 3
    Whatever it is, it's not a good practice and the code is not readable. I'd replace it with what it actually means so to not confuse other devs. – pid Jun 22 '15 at 13:02
  • @pid, the comparison function is probably often called in tight loops and other performance-critical situations. You're right in the general case, but avoiding two calls to `isNan()` may make the difference. – Frédéric Hamidi Jun 22 '15 at 13:04
  • @pid, my understanding was that those checks are faster and fewer characters than `isNaN`, which is sometimes important for popular frameworks. Not sure if this case is premature optimiziation. – zzzzBov Jun 22 '15 at 13:04
  • 1
    There's [this](http://stackoverflow.com/questions/25273042/when-does-a-a?lq=1)… – Bergi Jun 22 '15 at 13:04
  • @FrédéricHamidi and *zzzzBov* Yes I agree. Also, in a minified framework script (such as jquery.js) it may make totally sense. Still, I wouldn't write it in common application code where performance is second to maintainability. I think we all agree on all comments here :D – pid Jun 22 '15 at 13:10
  • Also worth noting that this behaves in the same way [as `NaN`s] for regex literals. See http://stackoverflow.com/questions/10776600/testing-for-equality-of-regular-expressions – blgt Jun 22 '15 at 13:13
  • @blgt: That question you link to seems to refer to a bug in ES3 (sic!) which was that one regex literal always produced the same object no matter how often it was evaluated. This "staticness" was fixed with ES5. – Bergi Jun 22 '15 at 13:31

0 Answers0