"When we compare two values using "==", And both values are of different types, then javascript tries to convert the type of one value.
This is not entirely true. In some cases both values are converted, for example with string-boolean comparisons. In that case both are converted to numbers.
As a general rule, yes, though not when comparing values of the same type (string to string or bool to bool, etc.).
"1" == true // Number("1") === Number(true)
// but
"a" == "a" // "a" === "a"
Also when you compare an object with a primitive, the object will first go through a more generic "to primitive" conversion first before the comparison is made. If no primitive is derived, an error is thrown. Otherwise that object's primitive value will go through the normal comparison treatment which may include converting to a number if not the same type of the primitive to which its being compared.
11
u/senocular Jul 17 '21
This is not entirely true. In some cases both values are converted, for example with string-boolean comparisons. In that case both are converted to numbers.
There's also an exception with undefined/null comparisons: