JavaScript comparison operators: Identity vs. Equality

Hristo picture Hristo · Mar 27, 2011 · Viewed 35.4k times · Source

I've been trying to understand the difference between JavaScript's comparison operators: identity and equality. From what I've read, if you check the equality of two objects using ==, JavaScript will try to figure out if they are the same type and, if not, try to get them to that same type. However, === doesn't behave in the same manner. So as an example:

var n = "1";
console.log(n==1);        // outputs true
console.log(n===1);       // outputs false

So what is the difference between these "identity" operators and the regular equality operators? What is the benefit of having both?

Are there differences in performance? I would think that the identity operator would be faster since it doesn't do conversion.

Also, how do these differ when it comes to more complex objects, like arrays? Most importantly, what do conventions say about when one should be used over the other, why?

Answer

Michael Copeland picture Michael Copeland · Mar 27, 2011

The equality operator will attempt to make the data types the same before making the comparison. On the other hand, the identity operator requires both data types to be the same as a prerequisite.

There are quite a few other posts out there similar to this questions. See:

How do the PHP equality (== double equals) and identity (=== triple equals) comparison operators differ? (has a nice comparison chart)
Which equals operator (== vs ===) should be used in JavaScript comparisons?

In practice, the identity operator comes in really handy when you want to be certain that a boolean value is true or false since...

1 == true     => true
true == true  => true
1 === true    => false
true === true => true