Why you should use Object.is() in equality comparison
We all know that JavaScript is loosely typed and in some cases it fall behind specially when it comes to quality comparison with ‘==’, comparing with ‘==’ gives unexpected results due to whats called coercion or casting “converting one of the 2 operands to the other’s type then compare”.
0 == ' ' //true
null == undefined //true
[1] == true //true
So they provided us with the triple equal operator ‘===’ which is more strict and does not coerce operands, However comparing with ‘===’ is not the best solution you can get:
NaN === NaN //false
The great news that in ES6 there is the new ‘Object.is()’ which is better and more precise it has the same features as ‘===’ and moreover it behaves well in some special cases:
Object.is(0 , ' '); //false
Object.is(null, undefined); //false
Object.is([1], true); //false
Object.is(NaN, NaN); //true
Mozilla team doesn’t think that Object.is is “stricter” than ‘===’, they say that we should think of how this method deal with NaN, -0 and +0 but overall I think it is now a good practice in real applications.
Now this table illustrates..
References:
Use the 100 answers in this short book to boost your confidence and skills to ace the interviews at your favorite companies like Twitter, Google and Netflix.
GET THE BOOK NOWA short book with 100 answers designed to boost your knowledge and help you ace the technical interview within a few days.
GET THE BOOK NOW