0

I have noticed that you can compare dates like this in Javascript:

const a = new Date('2020')
const b = new Date('2019')

a > b    // true
a >= b   // true
a < b    // false

But Date is an object:

typeof a // object

How does this work? Can we do it for any class?

rksh1997
  • 1,103
  • 7
  • 17
  • 1
    override the `.valueOf` method in your object – Bravo Aug 08 '21 at 09:12
  • 1
    It doesn’t overload them. The operators coerce the object to primitive types. `Date`s have `toString`, `valueOf`, and `Symbol.toPrimitive` properties. Read the [spec](//tc39.es/ecma262/#sec-islessthan) for details. – Sebastian Simon Aug 08 '21 at 09:13
  • [Duplicate](//google.com/search?q=site%3Astackoverflow.com+js+how+can+operators+be+used+with+Date) of [How does Javascript implement date comparison operator?](/q/43845122/4642212). – Sebastian Simon Aug 08 '21 at 09:14
  • @ rksh1997 - I've moved [my answer](https://stackoverflow.com/a/68699694/157247) to the dupetarget. – T.J. Crowder Aug 08 '21 at 10:02

0 Answers0