0

Is there any way to rewrite Array and Object prototype methods or other js behavior to make this:

console.log({} == []) // true
Konrad
  • 21,590
  • 4
  • 28
  • 64
  • 7
    No, there is not. – Pointy Oct 08 '22 at 15:52
  • @Pointy, couldn't `valueOf` be utilized here? – Konrad Oct 08 '22 at 15:53
  • 3
    You shouldn’t _want_ to do that. – ray Oct 08 '22 at 15:54
  • Why do you want JavaScript to pretend that two non-equal things are equal; what's the real problem that you're trying to solve with this "solution"? – David Thomas Oct 08 '22 at 15:54
  • 4
    @KonradLinkowski no, because that's only invoked if `==` type conversion thinks it should convert an object to a number. In `{} == []` they're both objects, so no type conversions are necessary. – Pointy Oct 08 '22 at 15:54
  • 5
    OP if you would explain what problem you are trying to solve, you might get better advice. – Pointy Oct 08 '22 at 15:55
  • Even if there was a way, it sounds like a very bad idea to do it. – Guillaume Brunerie Oct 08 '22 at 15:55
  • @Pointy Just wondering if can I rely on this mechanism working in team. We know that we can rewrite toString and ValueOf and it can break the code wich uses == when comparing primitives. – Dzianis Czaplia Oct 08 '22 at 15:59
  • 1
    @DzianisCzaplia ` == ` is the same as ` === ` because no type casts are needed. Type casting/conversion only happens when `==` is comparing different types. – Pointy Oct 08 '22 at 16:03

1 Answers1

1

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.

Ben Aston
  • 53,718
  • 65
  • 205
  • 331