Identity vs. Equality, A Battle Of Understanding! (=== vs. ==)

Why should we use the identity operator(===) instead of the equality(==) operator when comparing?

In Javascript we can find two kind of comparison operators, and even if both look fairly equal, they work on different ways. Let’s see.

The identity or strict operator (===) makes comparisons but not an auto type conversion, that means, if both values don’t have the same value and the same type, they won’t be considered as equal.

On the other hand, there is the equality or type-converting operator (==). This one compares two values, first it converts both values into a common type and after conversion is done, the equality comparison is performed exaclty as the === performs it.

Well, at this point I think everything is clear, and as Douglas Crockford’s said on his book “The Good Parts of Javascript”, it’s always better to use the identity operator.

Let’s mention some examples from his book:

Douglas Crockford’s Quote
‘’ == ‘O’ // false
0 == ‘’ // true
0 == ‘O’ // true
false == ‘false’ // false
false == ‘O’ // true
false == undefined // false
false == null // false
null == undefined // true
‘ \t\r\n ‘ == O // true
The lack of transitivity is alarming. My advice is to never use the evil twins. Instead, always use === and !==. All of the comparisons just shown produce false with the === operator.

As we can see, the equality operator is converting the two values, to a common type, and then compares them, that’s why ‘false’ and ‘O’ are equal because they initially were converted to a common type were converted to a common type. And the same occurs for the all other cases on the example.

But we need to be careful when using the identity operator to compare objects, let’s see the following cases:

{} === {} // false

var stuff1 = {px:1, py:1};

var stuff2 = {px:1, py:1};

stuff1 === stuff2 //false

var obj = {}

obj === obj //true

We have an explanation for that from Dr. Axel Rauschmayer on his post:

Objects have unique identities and are compared by reference, so, every object you create via an expression such as constructor or a literal is considered different from every other object; a fact that can be observed via the equality operator(===) and it’s very important to know that the identity operator compares objects by reference.Therefore, two objects are only equal if they have the same identity. It does not matter whether they have the same content or not.

Reference: http://www.2ality.com/2011/03/javascript-values-not-everything-is.html