Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
NeilFraser opened this issue Dec 17, 2024 · 2 comments

Comments

@NeilFraser
Copy link
Owner

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
Copy link
Owner Author

@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
Copy link
Owner Author

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant