Does this line from Underscore.js make equality testing really necessary?

I just looked at the _.isEqual Underscore.js function, and the code section looks something like this:

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

I am just wondering if there is any case where a third statement can be reached and rate it true ?

Edit: just to be clear, this is not my own code that I am talking about, I read the Underscore source, in particular this line , and I was wondering why they do it.

+6
source share
4 answers

I just looked through the Underscore repo and came across a short discussion where someone asked the same thing and it looks like it doesn't actually need to.

Following the algorithm defined by the ECMAScript language specification in section 11.9.6 and section 11.9.3 , it seems to show that no pair of values ​​should return true in the above case.

So, in short, no, this situation is impossible .

+3
source

The only situation where == and === reacts unexpectedly is to compare a string string ( "123" ) with a constructed string ( new String("123") ), which will not give the first test.

However, in the second test, it falls because the constructed string is of type object , but the literal is of type string .

Based on this, I would say no, the third statement can never be achieved and is evaluated as true.

+1
source

When you use the == operator, and expressions have different types, JavaScript will usually convert them to the same type before comparing.

For example, this can happen with null and undefined . null == undefined true, although null === undefined is false. However, typeof null is "object" , and typeof undefined is "undefined" . So, in this case, you should return false in the second expression.

You can read all the details in the specification (section 11.9.3), this is very important: http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-262.pdf

+1
source

My initial hunch was that it was due to a broken browser implementation.

However, after digging into git logs for this file, it looks like the corresponding line was in the first underscore.js procedure. (I will not hunt in the parent documentcloud core.js repo ...) You can see this on line 334 https://github.com/documentcloud/underscore/commit/02ede85b539a89a44a71ce098f09a9553a3a6890 .

So, now I assume that its just the crack that remained in it was never fully tested and was never cleaned.

+1
source

Source: https://habr.com/ru/post/897122/


All Articles