Why does this happen?
> new Date() - 50
1591281777205
> new Date() + 50
'Thu Jun 04 2020 10:43:01 GMT-0400 (Eastern Daylight Time)50'
console.log(new Date() - 50);
console.log(new Date() + 50);
I'm interested in this from a technical perspective but perhaps more so the perspective of language design. Is there any justification for this behavior or is it just the result of backwards compatibility or historical reasons? What constraints or mishaps down the long and windy road of JavaScript caused this madness?
Because +
is overloaded to mean either mathematical add
or string concatenation
. While -
only means mathematical subtract
. You can implement this behaviour your self by implementing the toPrimitive
function on your prototype. Like this:
function MyDate(n) {
this.number = n;
}
MyDate.prototype[Symbol.toPrimitive] = function(hint) {
if (hint === 'number') {
return this.number;
}
return `The date is: ${this.number}`;
};
var date = new MyDate(4);
console.log(date - 3);
console.log(date + 3);