Comparisons and sameness Between == , === and Object.is

Dheeraj Kumar Rao
JavaScript Kingdom
Published in
2 min readFeb 23, 2019

--

Picture credit :- https://www.rvcj.com

Here,we are going to discuss about comparison and equality between == , === and object.is().

First of all, I want to share about when the first time I saw Object.is() and where. I was writing the first time test case for React component in (Enzyme+jest). Then I got the first error in my terminal like this expected(received).toBe(expected) //object.is equality. After that, I have explored and now here we are. Thanks.

There are four equality algorithms

  1. Abstract Equality Comparison (==)
  2. Strict Equality Comparison (===): used by Array.prototype.indexOf, Array.prototype.lastIndexOf, and case-matching
  3. SameValueZero: used by TypedArray and ArrayBuffer constructors, as well as Map and Set operations, and also String.prototype.includes and Array.prototype.includes since ES2016
  4. SameValue: used in all other places

JavaScript provides three different value-comparison operations

  1. Double equals (==) will perform a type conversion when comparing two things, and will handle NaN, -0, and +0 specially to conform to IEEE Standard for Floating-Point Arithmetic (IEEE 754) (so NaN != NaN, and -0 == +0);
  2. Triple equals (===) will do the same comparison as double equals (including the special handling for NaN, -0, and +0) but without type conversion; if the types differ, false is returned.
  3. Object.is does no type conversion and no special handling for NaN, -0, and +0 (giving it the same behavior as === except on those special numeric values).

Why do we need Object.is ?

You might think, we already have strict equality (checks type + value) checking in JavaScript with the === operator, why do we need this function? Well strict equality isn't sufficient in some cases and they are the following:

Object.is() helps us by being able to compare these values to see if they are similar, something the strict equality operator cannot do.

Conclusion & Feedback

Triple equals(===) is called strict comparison operator in JavaScript. Object.is and strict comparison operator behave exactly the same except for NaN and +0/-0.

Please share your suggestion and feedback to me in comment box or DM me on my twitter(rao123dk). Your Suggestions and Feedback is Welcome.

Thanks for reading.

Happy Coding! Special thanks to MDN web docs for awesome explanations.

--

--