JS-Interpreter icon indicating copy to clipboard operation
JS-Interpreter copied to clipboard

Dates should coerce to strings not numbers when the plus operator is used

Open NeilFraser opened this issue 11 months ago • 3 comments

JavaScript coerces a Date to a string:

(new Date()) + 60000 "Wed Dec 18 2024 00:19:11 GMT+0100 (Central European Standard Time)60000"

JS-Interpreter coerces a Date to a number:

(new Date()) + 60000 1734477491561

I like JS-Interpreter's behaviour better, but what I like or don't like doesn't matter.

NeilFraser avatar Dec 17 '24 23:12 NeilFraser

@cpcallen Here's a bit of a mystery. This is pure spec-compliant JavaScript, no consideration of JS-Interpreter is needed.

Here's an Object with some hooks on toString and valueOf.

var o = new Object();
o.valueOf = function() {return 'o-value';};
o.toString = function() {return 'o-string';};

When '+' is used on that object, it calls valueOf.

o + 42

"o-value42"

Here's a Date with some hooks on toString and valueOf:

var d = new Date();
d.valueOf = function() {return 'd-value';};
d.toString = function() {return 'd-string';};

When '+' is used on that object, it calls toString.

d + 42

"d-string42"

How does '+' behave differently with an Object vs a Date?

NeilFraser avatar Dec 18 '24 09:12 NeilFraser

Ah, there's a specific exception for Date objects: https://262.ecma-international.org/5.1/#sec-11.6.1

No hint is provided in the calls to ToPrimitive in steps 5 and 6. All native ECMAScript objects except Date objects handle the absence of a hint as if the hint Number were given; Date objects handle the absence of a hint as if the hint String were given.

Still not sure what this means, but it's definitely the loose thread I need to pull.

NeilFraser avatar Dec 18 '24 09:12 NeilFraser

Any update on this?

BasBuur avatar Apr 11 '25 16:04 BasBuur