JavaScript Comparisons – Identity (===) Operator VS Equality (==) Operator

Equality Operator(==, !=) :

  • If the types of the two expressions are different, attempt to convert them to string, number, or Boolean.
  • NaN is not equal to anything including itself.
  • Negative zero equals positive zero.
  • null equals both null and undefined.
  • Values are considered equal if they are identical strings, numerically equivalent numbers, the same object, identical Boolean values, or (if different types) they can be coerced into one of these situations.
  • Every other comparison is considered unequal.

Identity Operator(===, !==) :
The Identity (===) operator behaves identically to the Equality (==) operator except no type conversion is done, and the types must be the same to be considered equal.

Differences

The == operator will compare for equality after doing any necessary type conversions. The === operator will not do the conversion, so if two values are not the same type === will simply return false. It’s this case where === will be faster, and may return a different result than ==. In all other cases performance will be the same.

To quote Douglas Crockford’s excellent JavaScript: The Good Parts

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. These are some of the interesting cases:

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.

For reference types == and === act consistently with one another (except in a special case).

The special case is when you compare a literal with an object that evaluates to the same literal, due to its toString or valueOf method. For example, consider the comparison of a string literal with a string object created by the String constructor.

Here the == operator is checking the values of the two objects and returning true, but the === is seeing that they’re not the same type and returning false. Which one is correct? That really depends on what you’re trying to compare. My advice is to bypass the question entirely and just don’t use the String constructor to create string objects.

Reference:

Leave a Reply

Your email address will not be published. Required fields are marked *

CAPTCHA