0

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?

Olian04
  • 6,480
  • 2
  • 27
  • 54
Brannon
  • 1,286
  • 2
  • 21
  • 36

2 Answers2

1

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);
Olian04
  • 6,480
  • 2
  • 27
  • 54
0

In Javascript If the left hand side of the + operator is a string, JavaScript will coerce the right hand side to a string.Its also a JavaScript String Operator that can also be used to add (concatenate) strings.

That why you are getting like this :

Click on the image

Sahil khan
  • 135
  • 7
  • It doesn't matter if the left or right operands are string, they'll be coerced to string: `5 + '5' === '55'` using the [*EvaluateStringOrNumericBinaryExpression* algorithm](https://tc39.es/ecma262/#sec-evaluatestringornumericbinaryexpression). Please don't post images of code, post text. – RobG Jun 04 '20 at 22:21