The JavaScript comparison table - All about `==` operator
Conquering Type Coercion in JavaScript. Period.
What are we talking about?
JavaScript has two similar, yet different, ways to compare data types. You can either test equality with ==
or ===.
Triple Equals
When using triple equals ===
in JavaScript, we test for both the type and the value we are comparing have to be the same. It is also called a “strict equality” or “identity” or “triple equals”.
42 === 42; // true
42 === "42"; //false
Double equals
When using double equals in JavaScript we test value after type coercion (if required) for both values under comparison. Double equals thus also performs type coercion, if required.
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.
Rules
Rule #1
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).
Rule #2
2 .Use ToPrimitive Conversion Based on values of comparison, type coercion occurs, let’s consider a internal function to convert so,
ToPrimitive(input, PreferredType?)
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 valueOf()
returns this
, while the default implementation of toString()
returns type information.
This is how the operators + and == call ToPrimitive()
.
Head to JavaScript Equality game to apply these rules and check your table here.
Cheers!
Step by step solution coming soon…