Truth and equality in JavaScript
When comparing values in JavaScript you have to know about implicit coercion.
Otherwise you may be surprised by unexpected results.
JavaScript automatically converts a value's data type – this is called coercion.
When you know the rules, you can use this concept as a powerful feature. If you don't, this is a major pitfall.
JavaScript knows two different equality operators:
They differ in how they treat values of different data types.
Equals operator: ==
The equals operator uses the Abstract Equality Comparison Algorithm to compare two values. The algorithm specifies, how values of different types are converted before comparing them. So the equals operator makes use of implicit coercion!
Strict equals operator: ===
The strict equals operator uses the Strict Equality Comparison Algorithm. If the types of the compared values differ, the result of the comparison is always false. There is no implicit coercion taking place!
Which one should I use?
There is no right and wrong. Both ==
and ===
can be useful.
Whenever possible I would use the strict equals operator (===
),
because its behaviour is much more reasonable for developers, who aren't used to JavaScript's coercion.
Tools like JSLint or JSHint
can be configured to check the use of equals/strict equals operators in your code base.