Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can I directly subtract two Date objects?

Tags:

javascript

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?

like image 551
DavidsKanal Avatar asked Nov 27 '22 01:11

DavidsKanal


1 Answers

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
like image 159
ps-aux Avatar answered Dec 10 '22 00:12

ps-aux