I always wondered. Clearly, if I do
const a = new Date();
, a will hold the reference to an instance of Date. It has methods, etc. Why is it, then, that I can subtract two dates using simple the - operator in between?
const a = new Date();
const b = new Date();
console.log(a - b);
Am I not subtracting two objects here? Does Date "extend" Number in some way? And, can I, for myself, define what those operators do for my own classes, similarly to how C# does it with operator overloading?
It is because of valueOf.
It does not apply only to Date
objects. You can make use of valueOf
in your objects as well.
const a = {}
a.valueOf = () => 100
console.log(a + 1) // 101
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With