When using triple equals
42 === 42; // true 42 === "42"; //false
It is also called “Abstract Equality Comparison” or “loose equality” or “double equals”.
1991 == "1991"; // true false == 0; //true
Type coercion means that two values are compared only after attempting to convert them into a common type.
Moral of the story is,
Always use triple equality unless you are sure about types of values being compared.
The following section talks about behavior of double equality , how type coercion works in general and how can you deduce equality table by yourself.
1 .Use truthy values
truthy value is a value that is considered true in a Boolean context. All values are truthy unless they are defined as
falsy (i.e., except for false, 0, -0, 0n, "", null, undefined, and NaN).
2 .Use ToPrimitive Conversion Based on values of comparison, type coercion occurs, let’s consider a internal function to convert so,
The optional parameter PreferredType indicates the final type of the conversion: it is either Number or String, depending on whether the result of
ToPrimitive() will be converted to a number or a string.
Conversion happens in following order,
- If input is primitive type, return it
- If input is an object. Call
input.valueOf(). If the result is primitive, return it.
- Else, call
input.toString(). If the result is primitive, return it.
- throw a
TypeError(indicating the failure to convert input to a primitive).
If PreferredType is Number, the above algorithm works in specified order.
If PreferredType is String, steps 2 and 3 are swapped.
The PreferredType can also be omitted; it is then considered to be String for dates and Number for all other values.
The default implementation of
this, while the default implementation of
toString() returns type information.
This is how the operators + and == call
Step by step solution coming soon…