The loose equality operator == is used to compare two values. Unlike strict equality, loose equality performs type coercion, converting one or both operands to the same type before comparing them.
Let us compare two values using the == operator to see how it differs from the common ===.
In the example above, the == operator compares numberValue, which is of the type number, with stringValue, which is of the type string. Since == performs type coercion, it converts the string 9 into the number 9. As the values match after coercion, the result is true.
Rules for Type Coercion
Understanding type coercion rules can help you predict the behavior of the == operator.
- When one operand is a
string, the other will be coerced into a string as well. Similarly, if one operand is a number, the other will be converted into a number.
- Boolean operands are converted into
numbers, where true becomes 1 and false becomes 0.
- When comparing an object to a primitive value (
string, number or boolean), the object is first converted into a primitive value before the comparison is performed.
- For
null or undefined, the comparison returns true only if both operands are either null or undefined.
However, type coercion can sometimes lead to unexpected results:
In this example, valueOne is a boolean, and valueTwo is a string. According to the rules, the boolean true is coerced into the number 1 but the string "true" does not convert to a number and remains "true". The values do not match after coercion, so the result is false.
Generally, it is recommended to avoid using loose equality. Strict equality comparisons are more predictable since they do not involve type coercion, and they may also execute faster as there is no need for additional type conversions.