Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

141
Views
Can I intercept/trap object behavior on comparison for equality

Playing around with Javascript objects is fun, and annoying:

const MyObject = function(value)  {
  let _myObject = {
    [Symbol.valueOf]() {
      return value
    },
    [Symbol.toPrimitive]() {
      return value
    },
  }
  return _myObject
}

let o = new MyObject("a")
let p = new MyObject("b")

o == "a"
# true

p == "a"
# false

o < p
# true

p < o
# false

p + "-foo"
# 'p-foo'

Having custom objects behave like primitive types looks potentially useful and intuitive! Until you try something like this:

let o = new MyObject("a")
let p = new MyObject("a")

o == "a"
# true

p == "a"
# true

o == p
# false

Javascript will (quite sensibly) return false when comparing two objects for equality.

Would there be any way to hack around the apparent “inconsistency” arising in a case like this? (Maybe some clever usage of proxies/Proxy handlers? )

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Can I intercept/trap object behavior on comparison for equality

No, you can't. The behavior of == is governed by the IsLooselyEqual abstract operation in the specification, which just hands off to IsStrictlyEqual when the operands both have the same type (and all objects are considered the same type in JavaScript). With the IsStrictlyEqual operation (===), when both of the operands are objects, the result is based entirely on whether they're the same object. There's no trap in there that you can hook into, not even with a Proxy.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!