Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this line from Underscore.js doing equality checking actually necessary?

I've just been looking at the _.isEqual function of Underscore.js and a section of the code goes something like this:

if (a === b) return true;

if (typeof a !== typeof b) return false;

if (a == b) return true;

I'm just wondering if there's any case where the third statement could be reached and evaluate to true?

Edit: Just to be clear, this isn't my own code I'm talking about, I'm reading the source of Underscore, in particular, this line and I was curious about why they're doing that.

like image 707
nickf Avatar asked Sep 12 '11 01:09

nickf


2 Answers

I've just been browsing through the Underscore repo and came across a short discussion where someone asked the exact same thing, and it looks like it is actually unnecessary.

Following the algorithm defined by the ECMAScript Language Specification in section 11.9.6 and section 11.9.3 seems to show that no pair of values should return true in the above case.

So, in short, no, that situation is not possible.

like image 176
nickf Avatar answered Oct 04 '22 05:10

nickf


The only situation where == and === react unexpectedly is when comparing a literal string ("123") to a constructed string (new String("123")), which would fail the first test.

However, on the second test it gets caught because the constructed string has the type object, but the literal has the type string.

Based on that, I'd say no, the third statement can never be reached, and evaluate to true.

like image 29
Joe Avatar answered Oct 04 '22 03:10

Joe