JavaScript Basics: Object.is

You may have heard of the book JavaScript: The Good Parts (Yahoo Press, December 2008) by Douglas Crockford. The name, obviously, implies that JavaScript has bad parts, too. The equality operator == is one aspect of JavaScript that is considered a bad part. Crockford writes in this book:

“JavaScript has two sets of equality operators: === and !==, and their evil twins == and !=. The good ones work the way you would expect. If the two operands are of the same type and have the same value, then === produces true and !== produces false. The evil twins do the right thing when the operands are of the same type, but if they are of different types, they attempt to coerce the values. The rules by which they do that are complicated and unmemorable.”

So the problem with the == operator is that it performs unexpected and complicated type conversions. For this reason, it is recommended that you always use === and never use ==.

Object.is is yet a new addition to JavaScript that tests for equality. It behaves like the === operator, with two exceptions: Contrary to the === operator, it treats +0 and -0 as not equal, and it treats NaN and Number.NaN as equal. Otherwise, it behaves like ===. In other words, it returns true if both operands are undefined, both are null, both are true or false, both are strings with the same length and the same characters, both are the same object, or both are numbers with the same value.

Here are a few examples:

    Object.is("hi", "hi"); // true
    Object.is(undefined, null); // false
    Object.is("", false); // false
    Object.is(+0, -0); // false
    +0 === -0; // true
    Object.is(NaN, Number.NaN); // true
    Number.NaN === NaN; // false

It is evident that Object.is is the best way to test for equality in JavaScript.


Related Posts

H2
H3
H4
3 columns
2 columns
1 column
Join the conversation now
Logo
Center