JavaScript comparison operators: Identity vs. Equality

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?


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

The difference is that ==, <=, >= and != will do type coercion — for example, force a string to be evaluated as a number. ===, <==, >==, and !== will not do type coercion. They will compare a string to a number, and since the string "1" is not the same as the numeric value 1, the result is false.

Reference is here:
https://developer.mozilla.org/en/JavaScript/Reference/Operators/Comparison_Operators