Is there any way to rewrite Array and Object prototype methods or other js behavior to make this:
console.log({} == []) // true
Is there any way to rewrite Array and Object prototype methods or other js behavior to make this:
console.log({} == []) // true
The abstract equality operator (==
) coerces its operands before performing the comparison if those operands are of different basic types. The basic types in JS are Undefined, Null, Number, BigInt, Boolean, String, Symbol, and Object.
Both of the operands in your example are of type Object (although one is an instance of Array (still an object!), and one isn't), so no coercion occurs: a straightforward value-of-the-reference comparison is made (and this will always be false
for two different objects).
You can kind-of hack what you want to do by forcing a manual conversion of each operand to a primitive before performing the abstract equality comparison. By forcing a conversion to a primitive you able to hook into the coercion process by overriding Object#valueOf
or implementing your own @@toPrimitive
method.