Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MDN "Object.is" alternative proposal

I have read the MDN page on the "Object.is" method. It gives an alternative code for the browsers that do not provide this method:

if (!Object.is) {
    Object.is = function(v1, v2) {
        if (v1 === 0 && v2 === 0) {
            return 1 / v1 === 1 / v2;
        }
        if (v1 !== v1) {
            return v2 !== v2;
        }
        return v1 === v2;
    };
}

The question is simple: when can the second "if" be true ?

Thank you for your attention.

like image 777
Clem Avatar asked Jan 31 '14 14:01

Clem


Video Answer


1 Answers

It kinda is written in the same article:

This is also not the same as being equal according to the === operator. The === operator (and the == operator as well) treats the number values -0 and +0 as equal, and it treats Number.NaN as not equal to NaN.

The logic is that NaN !== NaN is the only case in which the !== operator returns true on the same variable, so it must be about NaN comparison. It then does the same check on v2 and returns true of false based on the outcome: if v2 comparison is true, it's about NaN compared to NaN so return true, if not then return false because NaN is never the same as something that isn't NaN.

like image 152
gpgekko Avatar answered Sep 28 '22 18:09

gpgekko